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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit