Min stack
A stack that can also report its minimum value in O(1), using a second stack that tracks the running minimum.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Keep a second stack the same height as the first. Each time a value is pushed, also push the smaller of that value and the current minimum. The top of the min stack is always the minimum of everything still on the data stack, so GetMin is just a Peek.
Code
public class MinStack {
readonly Stack<int> data = new();
readonly Stack<int> mins = new();
public void Push(int x) {
data.Push(x);
mins.Push(mins.Count == 0 ? x : Math.Min(x, mins.Peek()));
}
public void Pop() {
data.Pop();
mins.Pop();
}
public int Top() => data.Peek();
public int GetMin() => mins.Peek();
}static class MinStack {
private final Deque<Integer> data = new ArrayDeque<>();
private final Deque<Integer> mins = new ArrayDeque<>();
void push(int x) {
data.push(x);
mins.push(mins.isEmpty() ? x : Math.min(x, mins.peek()));
}
void pop() {
data.pop();
mins.pop();
}
int top() { return data.peek(); }
int getMin() { return mins.peek(); }
}class MinStack {
stack<int> data;
stack<int> mins;
public:
void push(int x) {
data.push(x);
mins.push(mins.empty() ? x : min(x, mins.top()));
}
void pop() {
data.pop();
mins.pop();
}
int top() { return data.top(); }
int getMin() { return mins.top(); }
};class MinStack:
def __init__(self):
self.data = []
self.mins = []
def push(self, x: int) -> None:
self.data.append(x)
self.mins.append(x if not self.mins else min(x, self.mins[-1]))
def pop(self) -> None:
self.data.pop()
self.mins.pop()
def top(self) -> int:
return self.data[-1]
def get_min(self) -> int:
return self.mins[-1]Tips
- Pop both stacks together. The min stack is not touched independently, it only ever mirrors the data stack.
- This trick generalises: pair a stack with any running aggregate (min, max, sum) that needs O(1) access.
In the .NET library
A single stack of (value, minSoFar) pairs works just as well and uses the same O(n) space; two parallel stacks just keep the two concerns visually separate.