Min Stack (O(1) getMin)
Stack supporting push, pop, top and getMin in O(1) using an auxiliary stack or encoded values.
Visualization
Interactive visualization for Min Stack (O(1) getMin)
Main Stack
Empty
Min Stack (Auxiliary)
Empty
Min Stack Design:
- • Supports push, pop, top, and getMin - all in O(1) time
- • Uses an auxiliary stack to track minimum values
- • On push: add to main stack, update min stack if needed
- • On pop: remove from both stacks
- • getMin: return top of min stack
- • Space Complexity: O(n) for auxiliary stack
- • Applications: Stock span, monotonic problems, expression evaluation
Interactive visualization with step-by-step execution
Implementation
1class MinStack { private s:number[]=[]; private mins:number[]=[]; push(x:number){ this.s.push(x); if(!this.mins.length || x<=this.mins[this.mins.length-1]) this.mins.push(x);} pop(){ const v=this.s.pop(); if(v===this.mins[this.mins.length-1]) this.mins.pop(); return v;} top(){ return this.s[this.s.length-1]; } getMin(){ return this.mins[this.mins.length-1]; } }Deep Dive
Theoretical Foundation
Maintain an auxiliary structure to track the minimum alongside the main stack. Common approaches: (1) two stacks (values and current minima), (2) encode minima into pushed values to achieve O(1) amortized getMin with O(1) extra per element.
Complexity
Time
O(1)
O(1)
O(1)
Space
O(n)
Applications
Industry Use
Running minima in streams
Algorithm design patterns for stacks
Interview problems and competitive programming
Use Cases
Related Algorithms
Binary Search Tree (BST)
A hierarchical data structure where each node has at most two children, maintaining the property that all values in the left subtree are less than the node's value, and all values in the right subtree are greater. This ordering property enables efficient O(log n) operations on average for search, insert, and delete. BSTs form the foundation for many advanced tree structures and are fundamental in computer science.
Stack
LIFO (Last-In-First-Out) data structure with O(1) push/pop operations. Stack is a fundamental linear data structure where elements are added and removed from the same end (top). It's essential for function calls, expression evaluation, backtracking algorithms, and undo operations in applications.
Queue
FIFO (First-In-First-Out) data structure with O(1) enqueue/dequeue operations. Queue is a fundamental linear data structure where elements are added at one end (rear) and removed from the other end (front). Essential for breadth-first search, task scheduling, and buffering systems.
Hash Table (Hash Map)
A data structure that implements an associative array abstract data type, mapping keys to values using a hash function. Hash tables provide O(1) average-case time complexity for insertions, deletions, and lookups, making them one of the most efficient data structures for key-value storage. The hash function computes an index into an array of buckets from which the desired value can be found.