This is one of an interview question. You need to design a stack which holds an integer value such that getMinimum() function should return the minimum element in the stack.
For example: consider the below example
case #1 5 --> TOP 1 4 6 2 When getMinimum() is called it should return 1, which is the minimum element in the stack. case #2 stack.pop() stack.pop() Note: Both 5 and 1 are poped out of the stack. So after this, the stack looks like, 4 --> TOP 6 2 When getMinimum() is called is should return 2 which is the minimum in the stack.
Constriants:
- getMinimum should return the minimum value in O(1)
- Space constraint also has to be considered while designing it and if you use extra space, it should be of constant space.
I found this solution here
You could extend your original stack class and just add the min tracking to it. Let the original parent class handle everything else as usual.
Here is my version of implementation.
Here's the PHP implementation of what explained in Jon Skeet's answer as the slightly better space complexity implementation to get the maximum of stack in O(1).