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 used a different kind of stack. Here is the implementation.
Output:
Try it. I think it answers the question. The second element of every pair gives the minimum value seen when that element was inserted.
Here is my Code which runs with O(1). The previous code which I posted had problem when the minimum element gets popped. I modified my code. This one uses another Stack that maintains minimum element present in stack above the current pushed element.
I found a solution that satisfies all the constraints mentioned (constant time operations) and constant extra space.
The idea is to store the difference between min value and the input number, and update the min value if it is no longer the minimum.
The code is as follows:
Credit goes to: https://leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack
Here is the C++ implementation of Jon Skeets Answer. It might not be the most optimal way of implementing it, but it does exactly what it's supposed to.
And here is the driver for the class
Output: