Problem Description
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. The stack should implement the following functions:
- push(val): adds the element val to the stack.
- pop(): removes the element on the top of the stack.
- top(): retrieves the top element of the stack.
- getMin(): retrieves the minimum element currently in the stack.
Key Insights
- Use an auxiliary data structure to track the current minimum element.
- A common approach is to use two stacks: one regular stack for all elements and a second stack to keep track of the minimum values.
- When pushing a new element, push it onto the main stack and also update the min stack if the element is less than or equal to the current minimum.
- When popping, if the popped element is equal to the top of the min stack, pop from the min stack as well.
- This design guarantees that all operations (push, pop, top, getMin) run in constant time, O(1).
Space and Time Complexity
Time Complexity: O(1) per operation (push, pop, top, getMin) Space Complexity: O(n), where n is the number of elements in the stack, since an additional stack is used to keep track of minima.
Solution
The solution involves using two stacks:
- Main Stack: Stores all the elements.
- Min Stack: Stores the minimum elements encountered so far.
When an element is pushed, we compare it with the top of the min stack. If it is smaller than or equal to the current minimum, we also push it onto the min stack. For the pop operation, if the element being popped is the same as the top of the min stack, we pop from the min stack as well. This approach ensures that the getMin operation always returns the top element of the min stack, which is the current minimum in constant time.