LeetCode 155: Min Stack is a Medium stack problem. This Python walkthrough develops a paired minimum stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Stack |
| Reusable pattern | paired minimum stack |
| Complexity | O(1) time per operation and O(n) space |
Recognizing the pattern
A stack is appropriate when the newest unresolved item must be handled before older unresolved items.
For this problem specifically, store each pushed value together with the minimum at that stack depth so minimum queries never scan. The invariant worth writing beside the code is: The stored minimum in each entry equals the minimum of the stack prefix ending there.
Step-by-step algorithm
- Identify the input state consumed by
push(val)and initialize the data required by the paired minimum stack pattern. - Store each pushed value together with the minimum at that stack depth so minimum queries never scan.
- After each update, verify the page’s central invariant: The stored minimum in each entry equals the minimum of the stack prefix ending there.
- Finish only after the boundary behavior is covered: Duplicate minima must be preserved until every matching entry is popped.
Python solution
class MinStack:
def __init__(self):
self.stack = []
def push(self, val):
minimum = val if not self.stack else min(val, self.stack[-1][1])
self.stack.append((val, minimum))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def getMin(self):
return self.stack[-1][1]Reading the implementation
The main entry point is push(val). The named working state includes minimum; those variables make the paired minimum stack state visible instead of hiding it in incidental control flow.
The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, store each pushed value together with the minimum at that stack depth so minimum queries never scan.
Correctness argument
Initialization. The data structure starts with exactly the information known before any input element is processed.
Preservation. Store each pushed value together with the minimum at that stack depth so minimum queries never scan. Each update records the current item without invalidating earlier decisions; consequently, the stored minimum in each entry equals the minimum of the stack prefix ending there.
Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.
Complexity and trade-offs
O(1) time per operation and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Repeated rescanning can find the same dependency without a stack, but it usually hides the nesting invariant and costs more time. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
ms=MinStack(); ms.push(-2); ms.push(0); ms.push(-3); assert ms.getMin()==-3; ms.pop(); assert ms.top()==0 and ms.getMin()==-2Common mistakes and edge cases
- Problem-specific boundary: Duplicate minima must be preserved until every matching entry is popped.
- Pattern-level pitfall: Check emptiness before reading the top and decide whether an operator, delimiter, or node is consumed before or after the pop.
- Invariant check: after every update, confirm that the stored minimum in each entry equals the minimum of the stack prefix ending there.
Interview review checklist
- Explain why paired minimum stack matches the structure of this input.
- State the invariant in one sentence before tracing code: The stored minimum in each entry equals the minimum of the stack prefix ending there.
- Derive O(1) time per operation and O(n) space from how many times each element or state is visited.
- Test the boundary explicitly: Duplicate minima must be preserved until every matching entry is popped.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 71. Simplify Path · Next: 150. Evaluate Reverse Polish Notation