← Course home

Linear structures · Lesson 15 of 52

Monotonic stack patterns

Use a monotonic stack to resolve next-greater and related candidates in linear total work.

Full lessonAbout 10 min

You will learn to trace unresolved candidates and pops and derive linear total work from one push/pop per item.

Recommended first: Stack basics.

On this page 6 sections

The idea

next_greater on 2, 1, 2, 4, 3 returns 4, 2, 4, None, None.

A monotonic stack stores indexes that are still waiting for an answer. next_greater on 2, 1, 2, 4, 3 returns 4, 2, 4, None, and None. The stack holds indexes. When a larger value arrives, every index it beats is popped and that value is written as the answer. Indexes that remain at the end have no strictly greater value on their right. stock_spans uses the same waiting stack. On prices 100, 80, 60, 70, 60, 75, 85 the span at the 75 is 4, because the walk stops at a strictly higher price. largest_rectangle asks for the nearest shorter bar on each side. The area is height times the gap between those bars. On 2, 1, 5, 6, 2, 3 the largest area is 10. min_stack keeps the current minimum beside the values. After pushing 3, then 1, then 2, the minimum is 1. The shared rule is that a value leaves the stack only when a later value resolves it.

A worked trace

StepStateWhat changed
Scanindex = 0Index 0 holds 2. Answers are [None, None, None, None, None].
Scanindex = 1Index 1 holds 1. Answers are [None, None, None, None, None].
Scanindex = 2Index 2 holds 2. Answers are [None, 2, None, None, None].
Scanindex = 3Index 3 holds 4. Answers are [4, 2, 4, None, None].
Scanindex = 4Index 4 holds 3. Answers are [4, 2, 4, None, None].

Why it is correct

The stack stays ordered by the values at the stored indexes. A new value pops while the top is strictly smaller, so the top is the nearest unresolved candidate. Each pop writes an answer that will not change, because a later value is even farther to the right. The final leftovers are the positions with no greater neighbor, which is why their answers stay empty. The histogram uses two boundaries. A bar's width runs from the previous shorter bar to the next shorter bar, excluding those bars. Multiplying by the bar's height counts the rectangle that bar can support. The total work stays linear because each index is pushed once and popped at most once. The inner loop does not restart from the left.

A common mistake

A smaller neighbor does not answer a next-greater question.

What it costs

n indexes produce at most n pushes and n pops, so the time is linear and the stack uses linear extra memory. A fresh scan from each index would be quadratic. largest_rectangle is the same bound. One pass finds the next smaller bar and one pass finds the previous smaller bar. min_stack push, pop, and minimum are constant time because the minimum is stored, not searched. Use this pattern when every item waits for a later item and then never waits again. The scan is Θ(n) time and uses O(n) extra memory for the stack.

Run it

python
from bitsandbytes.stacks.next_greater import next_greaterprint(next_greater([2, 1, 2, 4, 3]))# prints: [4, 2, 4, None, None] 

Practice and next step

Open Stack parsing and expressions next. Parsing uses a stack to match brackets and to hold operators by precedence.

Implementation and tests Optional reference

Library code 3

  • bitsandbytes.stacks.next_greater
  • bitsandbytes.stacks.stock_span
  • bitsandbytes.stacks.largest_rectangle

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.

Step-by-step trace

Next greater values and a histogram

next_greater on 2, 1, 2, 4, 3 returns 4, 2, 4, None, None. The histogram area is 10.

index
0

State

  1. 0Nonecomparing
  2. 1Nonecomparing
  3. 2Nonecomparing
  4. 3Nonecomparing
  5. 4Nonecomparing

Index 0 holds 2. Answers are [None, None, None, None, None].

Practice feedback is loading. The lesson explanation remains available above.