Problem Statement
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
Problem link
Video Tutorial
You can find the detailed video tutorial hereThought Process
Since the Min Stack preserves most of the stack operations, it is natural to composite with a normal stack, the question is how do we keep the minimum value. Simply keeping the smallest value won't work since once that value is popped out from the stack, there is no way to track the next smallest value.One solution is to define an extra struct where it carries the minimum value before itself is popped out of the stack, basically the current minimum value so far seen in this stack. When newer element comes in, if value is smaller than the previous one, we update. Else ignore the larger values and carry over the smaller value.
Another solution is to keep two stacks. Similarly, the other stack only keeps the smallest value. We can only keep the smallest value or we can always push a value with the current smallest value seen far (essentially similar to solution one).
Solutions
Define own structure to carry over the minimum value so far
Time Complexity:O(1) Push, Pop, Top, GetMin
Space Complexity: O(N) , N is the total number of nodes, used extra class storage, negligible in practice.
Use two stacks.
As described above, we simply keep a minimum stack. Below implementation only pushes the smallest value, and when pop, need to peek the stack.Time Complexity: O(1),Push, Pop, Top, GetMin
Space Complexity: O(N) , N is the total number of nodes