Min Stack

Stack with O(1) getMin — each entry carries the min of itself and everything below.

Medium
Time O(1) per op Space O(n)
LeetCode
3 min read
design stack

Problem#

Design a stack supporting push, pop, top, and getMin — all in O(1).

Examples#

  • push(-2); push(0); push(-3); getMin()-3.
  • pop(); top()0; getMin()-2.

Constraints#

  • -2^31 <= val <= 2^31 - 1, up to 3 * 10^4 calls.

Approach#

Stack of pairs (value, currentMin). On push, the new min is min(val, prevMin). On pop, the prior min naturally restores.

Solution#

Min Stack
class MinStack {
vector<pair<int,int>> st; // {val, minSoFar}
public:
void push(int val) {
int m = st.empty() ? val : min(val, st.back().second);
st.push_back({val, m});
}
void pop() { st.pop_back(); }
int top() { return st.back().first; }
int getMin() { return st.back().second; }
};

Editorial#

Carrying the running minimum alongside each value makes getMin trivial. Popping does the right thing for free since the prior frame already stored its own min. Space doubles in the worst case — a fine trade for O(1) queries.

Complexity#

  • Time: O(1) per op.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.