Algo-Sim › Low-Level Design
Min Stack
Medium · Low-Level Design · step through it in Java, Python and C++ on your own input
A stack with O(1) getMin: every entry stores the minimum of itself and everything below it.
Problem
Design a stack that supports push(val), pop(), top() and getMin(), which returns the smallest value currently on the stack. Every operation must take constant time.
Constraints
- Every method is O(1)
- -2³¹ ≤ val ≤ 2³¹ − 1
- pop, top and getMin are only called on a non-empty stack
- Up to 3 · 10⁴ calls
Edge cases to test
- Pushing the same minimum twice, then popping one
- Negative values
- getMin after popping the minimum
Follow-up questions
- Can you save memory?
- Keep a second stack that only gets a value when it is ≤ the current minimum, or store differences from the minimum.
- What about a min-queue?
- Two min-stacks make a queue with O(1) amortized min, or use a monotonic deque.
Solution
Java
class MinStack {
// Each entry keeps its value and the minimum of everything at or below it.
private final Deque<int[]> stack = new ArrayDeque<>();
public void push(int val) {
int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
stack.push(new int[] {val, min});
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek()[0];
}
public int getMin() {
return stack.peek()[1];
}
}Python
class MinStack:
# Each entry keeps its value and the minimum of everything at or below it.
def __init__(self):
self.stack = []
def push(self, val):
low = val if not self.stack else min(val, self.stack[-1][1])
self.stack.append((val, low))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def getMin(self):
return self.stack[-1][1]C++
#include <bits/stdc++.h>
using namespace std;
class MinStack {
public:
// Each entry keeps its value and the minimum of everything at or below it.
deque<vector<int>> stack = {};
void push(int val) {
int min = stack.empty() ? val : std::min(val, stack.back()[1]);
stack.push_back(vector<int>{val, min});
}
void pop() {
stack.pop_back();
}
int top() {
return stack.back()[0];
}
int getMin() {
return stack.back()[1];
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Logger Rate Limiter (Easy)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)