AlgoLounge

Min Stack

easy

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.

Example

MinStack 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

Constraints

  • -2³¹ <= val <= 2³¹ - 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks
  • At most 3 * 10⁴ calls will be made to push, pop, top, and getMin

How the tests work: each test is a sequence of calls. operations[i] is the method called with arguments[i]; the first entry constructs the class. The expected output lists what every call returns — null for the constructor and for methods that return nothing.

TypeScript
Loading editor…
List of test cases (10)
Case 1
operations = ["MinStack","push","push","push","getMin","pop","top","getMin"]
arguments = [[],[-2],[0],[-3],[],[],[],[]]
Case 2
operations = ["MinStack","push","push","push","getMin","getMin"]
arguments = [[],[5],[3],[7],[],[]]
Case 3
operations = ["MinStack","push","getMin","push","getMin","pop","getMin"]
arguments = [[],[2],[],[1],[],[],[]]
Case 4
operations = ["MinStack","push","push","push","pop","getMin"]
arguments = [[],[1],[2],[3],[],[]]
Case 5
operations = ["MinStack","push","push","top","pop","top","getMin"]
arguments = [[],[1],[2],[],[],[],[]]
Case 6
operations = ["MinStack","push","push","push","getMin","pop","getMin","pop","getMin"]
arguments = [[],[-1],[-2],[-3],[],[],[],[],[]]
Case 7
operations = ["MinStack","push","push","getMin","push","getMin","pop","getMin"]
arguments = [[],[5],[3],[],[1],[],[],[]]
Case 8
operations = ["MinStack","push","getMin","push","getMin","push","getMin","push","getMin"]
arguments = [[],[4],[],[2],[],[5],[],[1],[]]
Case 9
operations = ["MinStack","push","push","push","push","getMin","pop","getMin","pop","getMin","pop","getMin"]
arguments = [[],[3],[5],[2],[4],[],[],[],[],[],[],[]]
Case 10
operations = ["MinStack","push","push","push","top","getMin"]
arguments = [[],[-3],[2],[-1],[],[]]