Facebook Pixel
Min Stack
Medium

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Example:

Input:
  MinStack minStack = new MinStack();
  minStack.push(-2);
  minStack.push(0);
  minStack.push(-3);
  minStack.getMin(); // returns -3
  minStack.pop();
  minStack.top();    // returns 0
  minStack.getMin(); // returns -2
Test Cases

Test Cases

Input
11
push -2
push 0
push -3
getMin
pop
top
getMin
push -4
getMin
pop
getMin
Expected Output
-3
0
-2
-4
-2
Step 1
Step 2
Step 3
Step 1: Identify the Pattern
Min Stack
Medium

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Example:

Input:
  MinStack minStack = new MinStack();
  minStack.push(-2);
  minStack.push(0);
  minStack.push(-3);
  minStack.getMin(); // returns -3
  minStack.pop();
  minStack.top();    // returns 0
  minStack.getMin(); // returns -2
Test Cases

Test Cases

Input
11
push -2
push 0
push -3
getMin
pop
top
getMin
push -4
getMin
pop
getMin
Expected Output
-3
0
-2
-4
-2
Step 1
Step 2
Step 3
Step 1: Identify the Pattern