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:
push(val)— pushes an element onto the stackpop()— removes the element on top of the stacktop()— returns the top elementgetMin()— retrieves the minimum element in the stack
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.
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.
