Loading practice problems…
Loading your practice workspace…
Loading code editor…
25 / 29
Sign in
Algorithms/Stack

Min Stack

medium30 min

Process a sequence of MinStack operations. push, pop, top, and getMin must all run in constant time.

Return one output per operation. Constructors, push, and pop produce null; top and getMin produce numbers.

Example 1

Inputoperations = ["MinStack", "push", "push", "push", "getMin", "pop", "top", "getMin"], values = [[], [-2], [0], [-3], [], [], [], []]

Output[null, null, null, null, -3, null, 0, -2]

After the pushes, the minimum is -3. Popping -3 leaves [-2, 0], so top returns 0 and getMin returns -2. The constructor, pushes, and pop each return null.

Example 2

Inputoperations = ["MinStack", "push", "getMin", "top"], values = [[], [5], [], []]

Output[null, null, 5, 5]

After pushing 5, it is the only item, so both getMin and top return 5. The constructor and push each return null.

Constraints

  • At most 30,000 operations are performed.
  • pop, top, and getMin are called only on a non-empty stack.
StackDesign