Min Stack Design - aloalgo

Min Stack Design

Medium

Design a stack that supports push, pop, peek, and retrieving the minimum element in constant time.

Your MinStack class should have the following methods:

  • push(x): Pushes element x onto the stack.
  • pop(): Removes the element on peek of the stack.
  • peek(): Gets the peek element.
  • getMin(): Retrieves the minimum element in the stack.

Example 1

Input
m = MinStack()
m.push(2)
m.push(0)
m.push(1)
m.get_min()
m.pop()
m.peek()
m.get_min()
Output
[0, 1, 0, 0]
Explanation:
  1. Push 2
  2. Push 1
  3. Peek: 1
  4. Get Min: 1
  5. Pop
  6. Peek: 2
  7. Get Min: 2
  8. Pop
  9. Push 5
  10. Get Min: 5

Example 2

Input
m = MinStack()
m.push(2)
m.push(1)
m.peek()
m.get_min()
m.pop()
m.peek()
m.get_min()
m.push(5)
m.get_min()
Output
[1, 1, 1, 2, 2, 2]
Explanation:
  1. Push 2
  2. Push 1
  3. Peek: 1
  4. Get Min: 1
  5. Pop
  6. Peek: 2
  7. Get Min: 2
  8. Pop
  9. Push 5
  10. Get Min: 5
Loading...
Input
m = MinStack()
m.push(2)
m.push(0)
m.push(1)
m.get_min()
m.pop()
m.peek()
m.get_min()
Output
[0, 1, 0, 0]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!