#155

Min Stack

MediumDesignHas vizStackDesign

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.

Example 1

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

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

After pushing -3, min is -3; after pop, top is 0 and min is -2.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • Methods pop, top and getMin operations will always be called on non-empty stacks.
  • At most 3 * 10^4 calls will be made to push, pop, top, and getMin.
Loading visualization…

Explanation

Min Stack is a Medium interview problem tagged [Stack, Design]. The winning approach is typically **Design**.

Intuition

Each structure covers a weakness of the other (lookup vs order).

Approach

Combine primitives (hash map + doubly linked list, two heaps, etc.) to hit the required complexities.

  1. List operations + target Big-O.
  2. Choose fields.
  3. Implement smallest correct version.
  4. Verify edge cases (empty, capacity 1).

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateDesign

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Design), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #155 Min Stack as understood when the pattern clicks.