Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `push(val: number): void` pushes the element `val` onto the stack. * `pop(): void` removes the element on the top of the stack. * `top(): number` gets the top element of the stack. * `getMin(): number` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Examples:** ```typescript const minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(1) all operations
- Space complexity: O(n)
Every stack operation is a constant-time push or pop on primitive arrays.
Follow-Up Questions Interviewers Ask About Min Stack
- Can you implement MinStack using only a single stack?
Yes, by pushing pairs [val, curMin] or storing differences (val - min) relative to the previous minimum.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.