Min Stack Auxiliary Tracking

Push onto an auxiliary stack that tracks the running minimum alongside the main stack, so pop and get_min stay O(1) with no rescanning.

PythonData Integrity

Code

pythonsnippet
30 lines
class MinStack:
    """Main stack plus an auxiliary stack tracking each prefix minimum."""

    def __init__(self):
        self.items = []
        self.minimums = []  # minimums[i] = min of items[0..i]

    def push(self, value):
        self.items.append(value)
        current = self.minimums[-1] if self.minimums else value
        self.minimums.append(min(current, value))

    def pop(self):
        self.minimums.pop()
        return self.items.pop()

    def peek(self):
        return self.items[-1]

    def get_min(self):
        return self.minimums[-1]

stack = MinStack()
for value in [5, 2, 8, 1, 3]:
    stack.push(value)
print("top:", stack.peek(), "min:", stack.get_min())
print("pop:", stack.pop(), "min now:", stack.get_min())
print("pop:", stack.pop(), "min now:", stack.get_min())
print("pop:", stack.pop(), "min now:", stack.get_min())
print("size:", len(stack.items))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

top: 3 min: 1
pop: 3 min now: 1
pop: 1 min now: 2
pop: 8 min now: 2
size: 2

How it works

The code’s whole job belongs to the class MinStack and the functions __init__, push, pop and peek.

The file repeats itself only inside for value in [5, 2, 8, 1, 3].

Watch out for

  • The install step does not exist — APIs come with the platform.

Putting it to use

Entry signature: def push(self, value)

Output lines are prefixed (top:, pop:, size:), so the printed lines stay attributable to their steps.

push is the public entry point; everything else in the file exists to support it.

Core lines

def push(self, value):
    self.items.append(value)
    current = self.minimums[-1] if self.minimums else value
    self.minimums.append(min(current, value))
def __init__(self):
    self.items = []
    self.minimums = []  # minimums[i] = min of items[0..i]
def get_min(self):
    return self.minimums[-1]

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. The file defines `__init__`, `push`, `pop` at load time.