PythonStudio
Interview Problems

Min Stack

easy · stack invariant

Implement MinStack(capacity); the nonnegative capacity argument is unused (the stack is unbounded). push(value) returns None. pop() returns the removed integer or None if empty. top() returns the most recent value or None if empty. get_min() returns the minimum current value or None if empty. All operations should take O(1) time, including repeated equal minimum values. Examples (JSON; null means Python None): Input: {"capacity": 0, "operations": [["push", [3]], ["push", [1]], ["get_min", []], ["pop", []], ["get_min", []]]} Output: [null, null, 1, 1, 3] Input: {"capacity": 0, "operations": [["pop", []], ["top", []], ["get_min", []]]} Output: [null, null, null]

Starter code

class MinStack:

    def __init__(self, capacity: int):
        """Implement this operation according to the statement."""
        pass

    def push(self, value: int) -> None:
        """Implement this operation according to the statement."""
        pass

    def pop(self) -> int | None:
        """Implement this operation according to the statement."""
        pass

    def top(self) -> int | None:
        """Implement this operation according to the statement."""
        pass

    def get_min(self) -> int | None:
        """Implement this operation according to the statement."""
        pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python compiler