Design a data structure that behaves like a standard stack but also supports retrieving the minimum element in constant time. You must implement four operations:All four operations must run in O(1) time. The challenge is that the minimum changes as elements are pushed and popped, and a simple variable tracking the current minimum is insufficient because when the minimum is popped, you need to know what the previous minimum was.
The solution uses an auxiliary stack that tracks the minimum at each state. Every time you push a value, you also push the current minimum onto the auxiliary stack. When you pop, you pop from both stacks. This way, the auxiliary stack always has the minimum for the current state at its top.The challenge here is that a single variable tracking the current minimum is not enough. When the current minimum is popped, you need to know what the previous minimum was. The auxiliary stack stores exactly this history: every time you push a value, the min stack also stores the minimum at that point.An alternative approach uses a single stack storing pairs of (value, currentMin), which achieves the same result with one stack instead of two. Both approaches run in O(1) time for all operations and use O(n) space.This data structure appears in real-world interview questions and in production systems where tracking the minimum or maximum of a dynamic set is required in constant time.
Example Input & Output
After pushing 3,5, min is 3. After pushing 2,1, min is 1. After popping 1, min reverts to 2.
Initial min is -2. After pushing -3, min becomes -3. After popping -3, min reverts to -2.
After pushing 1 then 2, top is 2 and min is 1. After popping 2, top becomes 1 and min stays 1.
Algorithm Flow
Solution Approach
The two-stack approach is the most intuitive. The main stack stores all values. The min stack stores the minimum at each step. When pushing, compare the new value with the top of the min stack and push the smaller one onto the min stack. When popping, pop from both stacks. The getMin operation simply returns the top of the min stack.
Time complexity is O(1) for all operations. Space complexity is O(n) for the two stacks combined.
Best Answers
import java.util.*;
class MinStack {
Stack<Integer> stack = new Stack<>();
Stack<Integer> minStack = new Stack<>();
public void push(int val) {
stack.push(val);
if (minStack.isEmpty() || val <= minStack.peek()) minStack.push(val);
}
public void pop() {
if (!stack.isEmpty()) {
int val = stack.pop();
if (!minStack.isEmpty() && val == minStack.peek()) minStack.pop();
}
}
public int top() { return stack.peek(); }
public int getMin() { return minStack.peek(); }
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
