Solve LeetCode 155: Min Stack in Python with a paired minimum stack approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete 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 |
What the problem is testing
Store each pushed value together with the minimum at that stack depth so minimum queries never scan.
Algorithm
- Store each pushed value together with the minimum at that stack depth so minimum queries never scan.
- Maintain this invariant: The stored minimum in each entry equals the minimum of the stack prefix ending there.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
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]Why this is correct
The proof follows the maintained state: The stored minimum in each entry equals the minimum of the stack prefix ending there. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(1) time per operation and O(n) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Duplicate minima must be preserved until every matching entry is popped.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 71. Simplify Path · Next: 150. Evaluate Reverse Polish Notation