155. Min Stack
Implementing a MinStack in Java
Stacks are one of the most fundamental data structures in computer science. While their basic functionality allows us to add and remove elements in a Last In First Out (LIFO) order, sometimes we want additional operations for specialized use cases. One common problem is how to efficiently retrieve the minimum element from the stack at any time, alongside standard stack operations like push() and pop().
In this post, we'll walk through the implementation of a MinStack, which not only behaves like a regular stack but also supports constant-time (O(1)) retrieval of the minimum element at any point.
Problem Definition: MinStack
We need to implement a special stack that supports the following operations in constant time:
push(int val): Pushes an element onto the stack.pop(): Removes the element on top of the stack.top(): Returns the element on top of the stack.getMin(): Retrieves the minimum element in the stack at any given moment.
The Challenge
The challenge here is ensuring that we can retrieve the minimum value in constant time. Normally, a stack doesn't keep track of the minimum element, and finding it would require scanning the entire stack, which would take O(n) time in the worst case. We need to design our stack to track the minimum in O(1) time without sacrificing the performance of the other operations.
Approach: Two Stacks
To solve this problem efficiently, we'll use two stacks:
- A primary stack,
stack, that holds all the elements. - A secondary stack,
minStack, that stores only the minimum values.
Here’s how it works:
- When we push a value onto the stack, we compare it with the current minimum (i.e., the top of
minStack). If the value is smaller than or equal to the current minimum, we push it ontominStackas well. - When we pop a value from the stack, if the popped value is the same as the top of
minStack, we pop fromminStacktoo. This ensures thatminStackalways holds the correct minimum value.
This way, we can always retrieve the minimum element from the top of minStack in constant time.
Code Implementation
Time and Space Complexity
Time Complexity: Each operation (
push,pop,top, andgetMin) takes constant timeO(1)because we only push, pop, or peek from stacks, which areO(1)operations.Space Complexity: In the worst case, every element is added to both
stackandminStack, so the space complexity isO(n), wherenis the number of elements in the stack.
Conclusion
This two-stack approach efficiently tracks the minimum value in a stack, allowing constant-time retrieval of the minimum while keeping the push and pop operations equally efficient. The key insight is using the minStack to mirror the minimum values at each point in time. This solution is a common interview problem and serves as a great example of how additional data structures can enhance the functionality of fundamental structures like stacks.
Comments
Post a Comment