π LeetCode 155: Min Stack
π LeetCode: 155.Min-Stack
π Problem Statement
title: βnoteβ tags: [dsa, problem-solving, leetcode, learning-note]
Key Notes & Pattern Insights β LC 155 Min Stack
Linked Theory Resource
- Obsidian Vault Theory Note: 07_min_stack.md
Core Pattern: Two Stacks (Auxiliary Min Stack)
-
Why standard Stack isnβt enough for
GetMin():- Standard stack searching requires scanning all elements ().
- Auxiliary
_minStackmaintains a running minimum synchronized with everyPushandPop.
-
Mathematical / Structural Invariant:
-
Key Pitfall:
- Duplicate minimum elements MUST be pushed onto
_minStackevery timeval <= currentMin.
- Duplicate minimum elements MUST be pushed onto
π‘ Multi-Solution Analysis
title: βcomplexityβ tags: [dsa, problem-solving, leetcode, learning-note]
Complexity Analysis β LC 155 Min Stack
Time Complexity
Push(val): constant time amortized stack operations.Pop(): constant time stack pop.Top(): constant time peek.GetMin(): constant time peek.
Space Complexity
- Auxiliary Space: extra space for the
_minStackparallel structure storing up to elements.
π οΈ C# Tips & Common Pitfalls
title: βtipsβ tags: [dsa, problem-solving, leetcode, learning-note]
Edge Case & Pitfalls Checklist β Min Stack
- Empty Stack Access: Ensure operations assume stack is non-empty as per LC constraints or handle empty states gracefully.
- Duplicate Minimum Values: When pushing duplicate min values (e.g. push
-2, push-2), ensure_minStackretains both so popping one duplicate doesnβt corrupt the minimum! - Integer Overflow: When storing difference
val - minin alternative approaches, watch out for integer underflow/overflow.
ποΈ Space to Practice
title: βpracticeβ tags: [dsa, problem-solving, leetcode, learning-note]
Practice Scratchpad & Strategy β LC 155 Min Stack
Strategy Breakdown
- Goal: Maintain an auxiliary stack
_minStackparallel to_stackthat keeps track of the current minimum element up to the current depth. - Push(val):
- Push
valonto_stack. - Push
Math.Min(val, _minStack.Peek())onto_minStack.
- Push
- Pop():
- Pop from both
_stackand_minStack.
- Pop from both
- GetMin():
- Peek at top of
_minStack.
- Peek at top of
Alternative Strategy (Space Optimization)
- Store tuples
(val, minSoFar)in a single stack, or store differencesval - min.