Python coding

Stack that knows its minimum

Write a class MinStack: a stack of integers where every operation runs in O(1).

  • push(x) puts x on top.
  • pop() removes the top value and returns it.
  • top() returns the top value without removing it.
  • get_min() returns the smallest value currently in the stack.

Values may be negative and may repeat. pop, top and get_min are never called on an empty stack.

The tests call the provided run_stack(ops): it applies each operation in order and returns the list of results (None for push, shown as null).

  • run_stack([["push",5],["push",3],["push",7],["get_min"],["pop"],["pop"],["get_min"],["top"]]) → [null,null,null,3,7,3,5,5]
  • run_stack([["push",2],["push",2],["pop"],["get_min"],["top"]]) → [null,null,2,2,2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

One variable holding the minimum is not enough: when the minimum is popped, you need the previous one back in O(1).

Hint 2

Store with each value the minimum of the stack at the moment it was pushed. The pair on top always answers get_min, and popping it restores the older minimum for free.

Hint 3

If you use a second stack of minimums instead, push onto it when the new value is less than or equal to its top; with strict less-than, duplicates of the minimum break it.

Solution and why it works
pythonO(1) per operation · O(n)
# --- your code ---
class MinStack:
    def __init__(self):
        self.items = []                  # (value, minimum so far) pairs

    def push(self, x: int) -> None:
        low = min(x, self.items[-1][1]) if self.items else x
        self.items.append((x, low))

    def pop(self) -> int:
        return self.items.pop()[0]

    def top(self) -> int:
        return self.items[-1][0]

    def get_min(self) -> int:
        return self.items[-1][1]


# --- provided: do not edit ---
def run_stack(ops: list[list]) -> list:
    stack = MinStack()
    return [getattr(stack, name)(*args) for name, *args in ops]

A stack only changes at its top, so the minimum of everything at or below an element is fixed for as long as that element stays. Store each value together with that minimum, computed when it is pushed: get_min reads the top pair, and a pop brings back the previous minimum automatically. Scanning for the minimum is O(n); a single min variable cannot recover once the minimum is popped. With a separate stack of minimums, use <= so duplicates survive.