Min Stack – Solution & Complexity
Solution Walkthrough
1. Start with the obvious simulation
- A plain array-backed stack makes
push,pop, andtopeasy. - But scanning the whole stack on every
getMinwould costO(n)per query.
2. Mirror the minimum state
- Maintain a second stack
minswith the same depth as the main stack. - At each depth, store the minimum value seen so far, so the current minimum is always
mins[-1].
3. Handle duplicates carefully
- Push the new minimum for every element, even if it matches the previous minimum.
- Then one pop removes both the top value and the corresponding minimum snapshot.
4. Final solution (all languages)
Two synchronized stacks keep every operation at constant time.
5. Complexity summary
- Time:
O(q)total forqoperations, soO(1)amortized and worst-case per operation. - Space:
O(q)in the worst case when every operation is a push.