Monotonic Stacks & Next Greater
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.

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.
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.
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>withpush,popandpeek, or a plainint[]with a top index for speed. In JavaScript an array withpush,popandat(-1)is the idiom.
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)