155. Min Stack
Asked at 36Bloomberg71Amazon60Apple60Microsoft55Google51Meta46UiPath64Snowflake54Infosys45Paytm100Zenefits100Odoo89Sigmoid87Snap80Tinkoff75Vimeo71Ozon70Lucid69AMD69Intel66Tripadvisor62Lyft61Oracle60Palo Alto Networks59Yandex57Walmart Labs53Uber52Salesforce52Nvidia48Citadel47Adobe44Flipkart43tcs42IBM35LinkedIn32Goldman Sachs21
Problem
Design a MinStack supporting push(val), pop(), top() and getMin() (the smallest value currently on the stack), each in O(1) time. pop, top and getMin are only called on a non-empty stack.
Example: push −2, push 0, push −3 → getMin() = −3; pop() → top() = 0, getMin() = −2
Store (value, min so far) pairs; the minimum is always at the top in O(1).
Complexity: O(1) per operation.
class MinStack:
def __init__(self):
self.st = [] # (val, current min)
def push(self, val: int) -> None:
self.st.append((val, min(val, self.st[-1][1]) if self.st else val))
def pop(self) -> None:
self.st.pop()
def top(self) -> int:
return self.st[-1][0]
def getMin(self) -> int:
return self.st[-1][1]
m = MinStack()
m.push(-2); m.push(0); m.push(-3)
assert m.getMin() == -3
m.pop()
assert m.top() == 0 and m.getMin() == -2
class MinStack {
private final Deque<int[]> st = new ArrayDeque<>(); // {val, min}
public void push(int val) {
st.push(new int[]{val, st.isEmpty() ? val : Math.min(val, st.peek()[1])});
}
public void pop() { st.pop(); }
public int top() { return st.peek()[0]; }
public int getMin() { return st.peek()[1]; }
}
type MinStack struct {
st [][2]int // (val, min so far)
}
func Constructor() MinStack {
return MinStack{}
}
func (this *MinStack) Push(val int) {
m := val
if n := len(this.st); n > 0 {
m = min(m, this.st[n-1][1])
}
this.st = append(this.st, [2]int{val, m})
}
func (this *MinStack) Pop() {
this.st = this.st[:len(this.st)-1]
}
func (this *MinStack) Top() int {
return this.st[len(this.st)-1][0]
}
func (this *MinStack) GetMin() int {
return this.st[len(this.st)-1][1]
}