Min Stack
Medium Design
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
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
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.
See the AI roundWatch the explanation
More Design
- LRU CacheAI round · Medium
- Find Median from Data StreamAI round · Hard
- Time Based Key-Value StoreAI round · Medium
- Serialize and Deserialize Binary TreeHard
- Insert Delete GetRandom O(1)Medium