πŸ“˜ 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


Core Pattern: Two Stacks (Auxiliary Min Stack)

  1. Why standard Stack isn’t enough for GetMin():

    • Standard stack searching requires scanning all elements ().
    • Auxiliary _minStack maintains a running minimum synchronized with every Push and Pop.
  2. Mathematical / Structural Invariant:

  3. Key Pitfall:

    • Duplicate minimum elements MUST be pushed onto _minStack every time val <= currentMin.

πŸ’‘ 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 _minStack parallel 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 _minStack retains both so popping one duplicate doesn’t corrupt the minimum!
  • Integer Overflow: When storing difference val - min in 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 _minStack parallel to _stack that keeps track of the current minimum element up to the current depth.
  • Push(val):
    • Push val onto _stack.
    • Push Math.Min(val, _minStack.Peek()) onto _minStack.
  • Pop():
    • Pop from both _stack and _minStack.
  • GetMin():
    • Peek at top of _minStack.

Alternative Strategy (Space Optimization)

  • Store tuples (val, minSoFar) in a single stack, or store differences val - min.