Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement a min stack

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

Python practice15 minStacks & QueuesIntermediateLast updated March 27, 2026

Problem statement

Design a stack that supports push(x), pop(), top(), and get_min() operations, each in O(1) time. The get_min method should return the minimum element currently in the stack. If an operation that queries the stack (top or get_min) is called when the stack is empty, behavior is undefined (tests will avoid invalid calls). Implement MinStack in Python.

Task

Implement the MinStack class with push(x), pop(), top(), and get_min() methods so that all operations run in O(1) time.

Examples

Sequence example

Input

push(2), push(0), push(3), push(0), get_min(), pop(), get_min()

Output

0 then 0

After pushes the minimum is 0; pop removes the last 0, but a previous 0 remains so min is still 0.

Input format

Operations will be invoked in test expressions by creating a MinStack instance and calling its methods.

Output format

Values returned by the evaluated expression (typically int).

Constraints

Number of operations in tests is small; expected O(1) per operation; no external libraries.

Samples

Sample 1

Input

(lambda s: (s.push(1), s.push(0), s.get_min())[-1])(MinStack())

Output

0

Push 1 then 0; get_min returns 0.