Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Stack

Keep the elements whose question is still open; each new element settles the ones it beats and waits its turn.


When it applies

73 74 75 71 69 72 69 71 75 stack (top) 72 pops 69 and 71: their answer is today each index is pushed once and popped once

A stack fits when each element's answer depends on the nearest element to one side that satisfies some comparison: the next larger value, the previous smaller one, the bracket that closes this one. Elements whose answer is still unknown sit on the stack. When a new element arrives, it settles every waiting element it beats, and those leave for good.

The stack stays in sorted order (a monotonic stack), because anything the new element beats is removed before the new element goes on. Each index is pushed once and popped at most once, so the loop is O(n) even though it contains a while.

Signals: "next greater", "previous smaller", "days until", "span", "largest rectangle", "valid brackets", "evaluate an expression", "undo". If you catch yourself scanning left or right from every index looking for the first bigger value, you want a stack.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

stack = []                    # indices still waiting
for i, x in enumerate(a):
    while stack and a[stack[-1]] < x:
        j = stack.pop()           # x settles j
        answer[j] = i             # first larger value after j
    stack.append(i)               # i waits for its own answer

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.