💡
Exercise 71

Min Stack 20 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1) time.

min_stack = MinStack() min_stack.push(-2) min_stack.push(0) min_stack.push(-3) min_stack.getMin() # → -3 min_stack.pop() min_stack.top() # → 0 min_stack.getMin() # → -2

The trick: maintain two stacks:

  • Main stack: Stores all values normally
  • Min stack: Stores the current minimum at each level
  • When pushing, the min stack stores min(val, current_min)
  • When popping, pop from both stacks

This way, getMin() just peeks at the top of the min stack — always O(1)!

📋 Instructions
Implement a MinStack class with push, pop, top, and getMin. Test with the provided sequence and print the results.
Keep a second stack (min_stack) that always has the current minimum on top. When pushing value x, push min(x, min_stack[-1]) onto min_stack. Pop from both stacks together.
🧪 Test Cases
Input
ms.getMin()
Expected
-3
Test case 1
Input
ms.top()
Expected
0
Boundary value
Input
ms.getMin()
Expected
-2
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.