Python 0155.py
class MinStack:
def __init__(self):
self.data = []
self.min = []
def push(self, val: int) -> None:
self.data.append(val)
lowest = val if not self.min else self.min[-1]
self.min.append(val if val < lowest else lowest)
def pop(self) -> None:
self.data.pop()
self.min.pop()
def top(self) -> int:
return self.data[-1]
def getMin(self) -> int:
return self.min[-1]
Difficulty
and has an acceptance rate of about 59% (4+ million submissions).
Typical patterns to solve this problem:
- Design
- Stack
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a MinStack class that supports the usual stack operations-push, pop, and top-while also offering constant-time retrieval of the current minimum element. Two internal lists are maintained: one (data) stores the stack’s values in insertion order, and the other (min) mirrors the size of data while keeping track of the smallest value seen up to each position. By updating the auxiliary list on every push and pop, the class guarantees that getMin can return the minimum without scanning the entire stack.
Initialization
When a MinStack instance is created, both internal containers are instantiated as empty Python lists. This establishes a clean state where no elements have been pushed yet.
def __init__(self):
self.data = []
self.min = []
The empty lists also serve as natural guards for edge conditions: attempts to access the top element or the minimum will raise an IndexError if the stack is empty, which aligns with typical stack semantics.
Push Operation
The push method adds a new integer to the stack and simultaneously updates the auxiliary minimum list. First, the value is appended to self.data. Then the method determines the current lowest value: if self.min is empty, the new value itself becomes the baseline; otherwise the last entry in self.min represents the minimum of the stack before the new element. The new entry in self.min is the smaller of the incoming value and this baseline, ensuring that each position in self.min reflects the minimum of the stack up to that depth.
def push(self, val: int) -> None:
self.data.append(val)
lowest = val if not self.min else self.min[-1]
self.min.append(val if val < lowest else lowest)
Edge handling is implicit: when the stack is empty (self.min is falsy), lowest is set to val, so the first entry in self.min correctly records the sole element as the minimum.
Pop Operation
Removing the top element is a symmetric operation. The method discards the last element from both self.data and self.min. Because the auxiliary list always mirrors the size of the primary stack, popping from both lists maintains alignment and guarantees that the next call to getMin will reflect the new minimum after removal.
def pop(self) -> None:
self.data.pop()
self.min.pop()
If the stack is empty, invoking pop will raise an IndexError, which is consistent with Python’s list behavior and signals an underflow condition to the caller.
Top Operation
The top method provides read-only access to the most recently pushed value without altering the stack. It simply returns the last element of self.data.
def top(self) -> int:
return self.data[-1]
Attempting to call top on an empty stack triggers an IndexError, mirroring the behavior of the underlying list and preserving the contract that a top element exists only when the stack contains items.
GetMin Operation
Retrieving the current minimum is a constant-time lookup of the last entry in the auxiliary list. Because self.min stores the minimum value up to each depth, the most recent entry always represents the minimum of the entire stack.
def getMin(self) -> int:
return self.min[-1]
When the stack is empty, this method raises an IndexError, which aligns with the expectation that a minimum cannot be defined for an empty collection.
Edge Cases Handled
The design gracefully addresses several boundary conditions. Pushing the first element correctly initializes both self.data and self.min with the same value, establishing a valid minimum. Subsequent pushes compare the incoming value against the existing minimum, ensuring that the auxiliary list always holds the correct running minimum. Popping the last element reduces both lists to empty, resetting the stack to its initial state without leaving stale references. Accessor methods (top and getMin) rely on Python’s list indexing semantics, automatically raising exceptions when the stack is empty, which provides clear feedback to the caller.
Performance Optimizations
The primary optimization lies in the use of a parallel auxiliary stack (self.min). By storing the minimum at each depth, the implementation avoids any need to traverse self.data when answering a minimum query. This yields constant-time performance for push, pop, top, and getMin. The auxiliary list also grows and shrinks in lockstep with the main stack, eliminating the overhead of additional bookkeeping structures. Because both lists are native Python arrays, appends and pops execute in amortized constant time, leveraging the underlying dynamic array implementation for efficient memory management.
ELI5 - Simplified Explanation
Imagine a special stack of toy blocks where each block is numbered. The first part sets everything up by creating two empty boxes to hold the information. One box keeps track of all the blocks stacked up, while the other box stays super focused on remembering the smallest number added so far.
When a new block is added, it goes onto the main stack. Then, the code plays a little game of comparison. It looks at the new number and the smallest number known before and picks the smaller of the two to save in the second box.
Taking a block away is simple. Both boxes say goodbye to their most recent entry at the exact same time so they always match up.
To peek at the very top block of the stack, the code just looks at the last item sitting in the first box. If the goal is to see the smallest number currently in the collection, the code peeks at the last item stored in that special second box that remembers the tiny numbers.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | C# | Rust | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| Dijkstra-Edu | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 239: Sliding Window Maximum
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality