MEDIUM NC#22 Stack
155. Min Stack
๐ Problem
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: - MinStack() initializes the stack object. - void push(int val) pushes the element val onto the stack. - void pop() removes the element on the top of the stack. - int top() gets the top element of the stack. - int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use auxiliary stack to track minimums
- โ When pushing, push to minStack if <= current min
- โ When popping, pop from minStack if removing the min
- โ Time: O(1) for all operations, Space: O(n)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse auxiliary stack to track minimums
- โขWhen pushing, push to minStack if <= current min
- โขWhen popping, pop from minStack if removing the min
Common Pitfalls
- โขTime: O(1) for all operations, Space: O(n)
๐งช Test Cases
Hidden tests on submit: 5
Test Case 1
Not run Input:
(() => { const minStack = new MinStack(); return minStack.push(-2); })(); Expected:
null Test Case 2
Not run Input:
(() => { const minStack = new MinStack(); minStack.push(-2); return minStack.push(0); })(); Expected:
null Test Case 3
Not run Input:
(() => { const minStack = new MinStack(); minStack.push(-2); minStack.push(0); return minStack.push(-3); })(); Expected:
null ๐ Code Editor
๐ค Output