Min Stack
Medium Design AI round
MinStack() is a stack of whole numbers, empty to begin with, that can also tell you the smallest number it holds.
push(val) puts val on top of the stack. pop() takes the number on top off the stack. top() returns the number on top and leaves it where it is.
getMin() returns the smallest number in the stack and leaves the stack as it is. A number pushed more than once is in the stack once for each push, so popping one copy of the smallest leaves the others, and the smallest is still that number.
Example 1
2 is the smallest while it is in the stack. Once it is popped, the smallest of 4 and 7 is 4 again, and 7 is on top.
Example 2
Example 3
Constraints
-10⁹ ≤ val ≤ 10⁹pop,topandgetMinare called only when the stack holds at least one number- at most
3 × 10⁵calls in all topush,pop,topandgetMin
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Design
- LRU CacheAI round · Medium
- Time Based Key-Value StoreAI round · Medium
- Find Median from Data StreamHard
- Serialize and Deserialize Binary TreeHard
- Insert Delete GetRandom O(1)Medium