3 ms·
I think you may have needed to clarify the question further. The solution you linked is more complex than what is actually being asked. The way you stated it t
by aleksiy123 5y ago
I think you may have needed to clarify the question further. The solution you linked is more complex than what is actually being asked.
The way you stated it the only requirement is O(1) runtime complexity on finding the min.
You are already using O(n) space for the stack so you should be fine using extra linear space.
The push and pop operations also don't necessarily have to be O(1) which makes this a lot simpler. You should clarify this in the interview.
the discussion section here should give you some ideas
https://leetcode.com/problems/min-stack/description/ https://leetcode.com/problems/min-stack/description/
The solution they are probably looking for is quite simple if a little tricky.
Each node in the stack should store two values (the value pushed, the min of the stack when that node was inserted)
This way you only have to compare the current value to the min at the top of the stack when inserting and don't have to find the min again when popping.
This gives O(1) findMin, push, pop and O(n) space.