Skip to main content

Min Stack

MediumPremium

Design a stack that supports the following operations in constant time:

  • push(x) – Push element x onto the stack.

  • pop() – Removes the element on the top of the stack.

  • top() – Get the top element.

  • get_min() – Retrieve the minimum element in the stack.

All operations must run in O(1) time.

You may assume that all input values are valid and that operations will be called on non-empty stacks where applicable.

Example

Input: operations = ["MinStack", "push", "push", "push", "getMin", "top", "pop", "getMin"] arguments = [[], [1], [2], [3], [], [], [], []] Output: expected = [None, None, None, None, 1, 3, None, 1]

Explanation -

Stack = [1, 2, 3], minimum is 1 throughout.

top() is 3, pop removes 3, getMin() still returns 1.