Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods
Design a stack that supports push, pop, top, and retrieving the minimum element, all in O(1) time. Implement the `MinStack` class: - `push(val)` pushes `val` onto the stack. - `pop()` removes the element on top. - `top()` returns the top element. - `getMin()` returns the minimum element currently in the stack. All operations are called on a valid (non-empty where required) stack.
+ 1 hidden test run on Submit.
An auxiliary stack records the minimum so far at each depth. Pushing stores min(val, currentMin) and popping removes from both, so getMin is always the top of the min-stack in O(1).
Run your code to see results.