Skip to the workspace
Pebellslearn by building
Monotonic Structures & Search on the Answer  ›  Lesson

Monotonic Stacks & Next Greater

Monotonic Stacks 28 minA stack kept in sorted order answers every nearest-bigger question in one pass

dsa / Monotonic Stacks & Next Greater

Explore each scene at your own pace.

01 · A quick recap, and what changes now

A quick recap, and what changes now

Monotonic Stacks & Next Greater

Definition
A monotonic stack is a stack kept in sorted order: when a new value arrives, items that it beats are popped off first. It finds the next greater or smaller value for every item in one O(n) pass, because each item is pushed and popped at most once.
In plain words
Picture people queuing up, each waiting to see someone taller than themselves. When a taller person arrives, everyone shorter in front is answered and leaves the queue. Nobody is ever checked more than a couple of times.

In short: keep a stack of items still waiting for an answer, in sorted order. When a new value arrives, pop everyone it beats — each popped item is dominated: something nearer and at least as extreme has shown up, so it can never be the answer for anything later. Every item is pushed once and popped at most once, so the whole scan is O(n) even though there's a loop inside a loop. One structure answers next-greater, next-smaller, previous-greater and previous-smaller — the only choice is which side records the answer and whether ties pop.

Five bars (40, 30, 35, 10, 50): 30 pops 40 off the stack, and 10 pops both 35 and 30 — each popped bar can never again be anyone's nearest smaller value

From here on the course builds Quarry, a search-and-storage engine: the kind of program that sits under a search box or an analytics dashboard, stores records, indexes them and answers queries about them. This section builds Quarry's query planner, the part that reads what the engine has been doing and decides what to do next. Its raw material is a latency trace: one number per request, the milliseconds that request took, in the order the requests arrived.

python

The worst request is easy. The planner's real questions are about neighbours: after this slow request, how long until an even slower one? Before it, where was the last faster one? Over how wide a stretch was this request the slowest thing happening? Asked naively, each question scans outwards from every request, and a trace of n requests costs O(n²). This lesson answers all of them in O(n) with one structure.

A quick recap, and what changes now

In the stacks lesson you met next_greater: walk left to right, keep a stack of indices still waiting for a bigger value, and let each new value answer every smaller one on top. The stack's values only ever decrease from bottom to top, so it is called a monotonic stack.

That was one question. There are really four, and they all use the same loop:

question scan pop the top while it is…
next greater (first later value that is bigger) left to right smaller than the new value
next smaller left to right bigger than the new value
previous greater (last earlier value that is bigger) left to right, read the top after popping smaller than or equal to the new value
previous smaller left to right, read the top after popping bigger than or equal to the new value

The first two record an answer when an item is popped: the arrival that pops it is its answer. The last two record an answer when an item is pushed: after the pops, whatever is left on top is the nearest earlier item that survived, and that survivor is the answer.

python

Why is it safe to throw 40 away when 30 arrives? Any later value that 40 is smaller than, 30 is smaller than too, and 30 is nearer. 40 can never again be the nearest smaller value to anything. That argument, "this item is dominated and can never be an answer again", is the whole technique. Every monotonic stack you write should come with one sentence saying why the popped item is useless.

❓ Cross-question — "Couldn't I just sort the trace and look things up?" Sorting throws away the one thing these questions are about, which is position. "The nearest faster request before this one" depends on what is near, not only on what is faster. A sorted copy tells you which values are smaller but not which of them is closest, and recovering that costs more than the stack's single pass. A monotonic stack keeps both orders at once: it is ordered by position because you push in arrival order, and ordered by value because you pop anything that breaks the sort.

Coming from Java/JS: in Java, use an ArrayDeque<Integer> with push, pop and peek, or a plain int[] with a top index for speed. In JavaScript an array with push, pop and at(-1) is the idiom.

What does this print?
lat = [40, 30, 35, 10, 50]
st, out = [], []
for x in lat:
    while st and st[-1] >= x:
        st.pop()
    out.append(st[-1] if st else -1)
    st.append(x)
print(out)
Scene 1 of 13
Project context and further resources
You're building a piece ofQuarry — the query planner
This piece — spike_reach(): For every request in a latency trace, how wide a stretch it is the slowest in.
Scenario A 300 ms request lands in the middle of a quiet trace. Quarry's planner reports how far its shadow reaches: every neighbouring request up to the first slower one on each side.
spike_reach.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
spike_reach(latencies) → listFor each request, the widest run of consecutive requests around it with nothing strictly slower.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.