1. Paired Auxiliary Min Stack
OptimalMaintain two parallel stacks: a primary data stack and an auxiliary min stack that records the running minimum value associated with each stack depth in O(1) time.
push, pop, top, and getMin all execute in constant O(1) time without any loops or traversals.
Consumes 2N space to store N primary elements and N associated running minimums.
How It Works
The Invariant: Every Stack Level Remembers Its Minimum
A normal stack easily provides O(1) push, pop, and top. The challenge is getMin():
- Scanning the stack takes O(n) time.
- If we only keep a single global variable
currentMin, when that minimum is popped off, we cannot know what the previous minimum was without scanning the entire remaining stack!
The Solution: History Tracking
Because stack operations strictly adhere to Last-In, First-Out (LIFO) ordering, the minimum of any prefix of the stack never changes as long as those elements remain in the stack!
- Maintain two stacks:
dataStack: Stores normal values.minStack: Stores the running minimum up to the current height.
- Push(val):
- Push
valontodataStack. - The new minimum is
min(val, minStack.top())(orvalifminStackis empty). - Push this new minimum onto
minStack.
- Pop():
- Pop simultaneously from both
dataStackandminStack. - The previous minimum is naturally restored at the top of
minStack!
- Top(): Return
dataStack.top(). - GetMin(): Return
minStack.top()in instant O(1) time.
Step-by-Step Dry Run
dataStack: [-2], minStack: [-2]. Current min = -2.
data: [-2]min: [-2]- +Guaranteed constant O(1) time for every operation
- +Simple and bug-resistant without integer-encoding math
- -Always duplicates every element in minStack even when items are strictly increasing
Reference Implementation
Complete implementation for Paired Auxiliary Min Stack in Python, JavaScript, Java, C++, and C.
class MinStack:def __init__(self):self.stack = []self.min_stack = []def push(self, val: int) -> None:self.stack.append(val)if not self.min_stack or val <= self.min_stack[-1]:self.min_stack.append(val)else:self.min_stack.append(self.min_stack[-1])def pop(self) -> None:self.stack.pop()self.min_stack.pop()def top(self) -> int:return self.stack[-1]def get_min(self) -> int:return self.min_stack[-1]if __name__ == "__main__":ms = MinStack()ms.push(-2)ms.push(0)ms.push(-3)print("Min:", ms.get_min()) # -3ms.pop()print("Top:", ms.top()) # 0print("Min:", ms.get_min()) # -2
class MinStack {
constructor() {
this.stack = [];
this.minStack = [];
}
push(val) {
this.stack.push(val);
if (this.minStack.length === 0 || val <= this.minStack[this.minStack.length - 1]) {
this.minStack.push(val);
} else {
this.minStack.push(this.minStack[this.minStack.length - 1]);
}
}
pop() {
this.stack.pop();
this.minStack.pop();
}
top() {
return this.stack[this.stack.length - 1];
}
getMin() {
return this.minStack[this.minStack.length - 1];
}
}
const ms = new MinStack();
ms.push(-2);
ms.push(0);
ms.push(-3);
console.log("Min:", ms.getMin()); // -3
ms.pop();
console.log("Top:", ms.top()); // 0
console.log("Min:", ms.getMin()); // -2import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
public static class MinStack {
private Deque<Integer> stack;
private Deque<Integer> minStack;
public MinStack() {
stack = new ArrayDeque<>();
minStack = new ArrayDeque<>();
}
public void push(int val) {
stack.push(val);
if (minStack.isEmpty() || val <= minStack.peek()) {
minStack.push(val);
} else {
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
public static void main(String[] args) {
MinStack ms = new MinStack();
ms.push(-2);
ms.push(0);
ms.push(-3);
System.out.println("Min: " + ms.getMin()); // -3
ms.pop();
System.out.println("Top: " + ms.top()); // 0
System.out.println("Min: " + ms.getMin()); // -2
}
}#include <iostream>
#include <stack>
#include <algorithm>
class MinStack {
private:
std::stack<int> s;
std::stack<int> minS;
public:
MinStack() {}
void push(int val) {
s.push(val);
if (minS.empty() || val <= minS.top()) {
minS.push(val);
} else {
minS.push(minS.top());
}
}
void pop() {
s.pop();
minS.pop();
}
int top() {
return s.top();
}
int getMin() {
return minS.top();
}
};
int main() {
MinStack ms;
ms.push(-2);
ms.push(0);
ms.push(-3);
std::cout << "Min: " << ms.getMin() << "\n"; // -3
ms.pop();
std::cout << "Top: " << ms.top() << "\n"; // 0
std::cout << "Min: " << ms.getMin() << "\n"; // -2
return 0;
}#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 30000
typedef struct {
int data[MAX_SIZE];
int minData[MAX_SIZE];
int topIndex;
} MinStack;
MinStack* minStackCreate() {
MinStack* obj = (MinStack*)malloc(sizeof(MinStack));
obj->topIndex = -1;
return obj;
}
void minStackPush(MinStack* obj, int val) {
obj->topIndex++;
obj->data[obj->topIndex] = val;
if (obj->topIndex == 0 || val <= obj->minData[obj->topIndex - 1]) {
obj->minData[obj->topIndex] = val;
} else {
obj->minData[obj->topIndex] = obj->minData[obj->topIndex - 1];
}
}
void minStackPop(MinStack* obj) {
if (obj->topIndex >= 0) {
obj->topIndex--;
}
}
int minStackTop(MinStack* obj) {
return obj->data[obj->topIndex];
}
int minStackGetMin(MinStack* obj) {
return obj->minData[obj->topIndex];
}
void minStackFree(MinStack* obj) {
free(obj);
}
int main(void) {
MinStack* ms = minStackCreate();
minStackPush(ms, -2);
minStackPush(ms, 0);
minStackPush(ms, -3);
printf("Min: %d\n", minStackGetMin(ms)); // -3
minStackPop(ms);
printf("Top: %d\n", minStackTop(ms)); // 0
printf("Min: %d\n", minStackGetMin(ms)); // -2
minStackFree(ms);
return 0;
}