Skip to content

Monotonic stacks and next greater values

A monotonic stack keeps its stored values in increasing or decreasing order. That order lets one new value resolve several earlier positions without repeated scans. Use this pattern when a problem asks for the next greater or smaller value, or a boundary set by such a value.

Read stacks first for Python’s append and pop operations. The examples use invented integer sensor readings. Save the Python blocks in page order, or download the source below. Run the script with uv run python monotonic_stacks.py.

Download the English captions for this video.

For each reading, return the distance to the first later reading that is strictly higher. Return zero when no later reading is higher. Equal readings do not satisfy the request. An empty input produces an empty answer, and the function must leave its input unchanged.

A direct solution scans every later position for each reading. On a decreasing input, that approach examines every pair and takes O(n²) time. Instead, keep indices whose answer remains unresolved in a stack. Indices retain both the earlier value and the position needed to calculate a distance.

def next_higher_distance(values: list[int]) -> list[int]:
"""Find the distance to the first strictly greater value on the right.
Args:
values: Integer readings in observation order. This list is unchanged.
Returns:
One distance per input position, or zero if no greater value follows.
"""
distances = [0] * len(values)
pending: list[int] = []
for index, value in enumerate(values):
while pending and values[pending[-1]] < value:
previous = pending.pop()
distances[previous] = index - previous
pending.append(index)
return distances
readings = [8, 6, 6, 9, 7, 10]
print("Readings:", readings)
print("Distances:", next_higher_distance(readings))
Readings: [8, 6, 6, 9, 7, 10]
Distances: [3, 2, 1, 2, 1, 0]

The stack contains unresolved indices in increasing index order. Their corresponding values are nonincreasing from bottom to top; equal values remain together. When a new value exceeds the top value, it resolves that top index. Continue until the stack is empty or the top value is at least the new value, then push the new index.

The trace prints each resolved index before it prints the remaining stack. The rightmost index is the top. It also prints the answer after each input. A zero remains provisional until the final input has been processed.

pending = []
distances = [0] * len(readings)
for index, value in enumerate(readings):
resolved = []
while pending and readings[pending[-1]] < value:
previous = pending.pop()
distances[previous] = index - previous
resolved.append(previous)
pending.append(index)
print("Read:", index, value, "Resolved:", resolved)
print("Pending indices:", pending)
print("Pending values:", [readings[item] for item in pending])
print("Distances:", distances)
assert distances == next_higher_distance(readings)
Read: 0 8 Resolved: []
Pending indices: [0]
Pending values: [8]
Distances: [0, 0, 0, 0, 0, 0]
Read: 1 6 Resolved: []
Pending indices: [0, 1]
Pending values: [8, 6]
Distances: [0, 0, 0, 0, 0, 0]
Read: 2 6 Resolved: []
Pending indices: [0, 1, 2]
Pending values: [8, 6, 6]
Distances: [0, 0, 0, 0, 0, 0]
Read: 3 9 Resolved: [2, 1, 0]
Pending indices: [3]
Pending values: [9]
Distances: [3, 2, 1, 0, 0, 0]
Read: 4 7 Resolved: []
Pending indices: [3, 4]
Pending values: [9, 7]
Distances: [3, 2, 1, 0, 0, 0]
Read: 5 10 Resolved: [4, 3]
Pending indices: [5]
Pending values: [10]
Distances: [3, 2, 1, 2, 1, 0]

Before each iteration, no pending index has encountered a strictly greater reading to its right in the processed prefix. Every index removed now receives its first such reading, because an earlier qualifying reading would already have removed it. If the top value is at least the current value, no index beneath it qualifies either. Values are no smaller toward the bottom. These facts preserve the invariant after each push.

After the last reading, unresolved indices have no greater value anywhere to their right. Their initial zero answers therefore remain correct. Use <, not <=, in this version; removing equal values would answer a different question.

Each index enters the stack once and leaves at most once. Across the whole loop, there are at most n pushes and n successful pops. Failed comparisons also contribute at most one per input iteration, so the function takes O(n) total time. These costs assume constant-time integer comparisons and amortized list operations.

One iteration can remove many indices, so its individual cost can be O(n). The linear bound describes the complete scan, despite the nested loops. The stack takes O(n) auxiliary space in a decreasing or constant input, and the returned answer also takes O(n) space. The trace repeatedly displays entire lists and can take O(n²) time; those displays are absent from the function.

for case, expected in [
([], []),
([5], [0]),
([5, 5], [0, 0]),
([5, 5, 6], [2, 1, 0]),
([1, 2, 3], [1, 1, 0]),
([3, 2, 1], [0, 0, 0]),
([-2, -3, -1], [2, 1, 0]),
]:
original = case[:]
answer = next_higher_distance(case)
assert answer == expected
assert case == original
print(case, answer)
[] []
[5] [0]
[5, 5] [0, 0]
[5, 5, 6] [2, 1, 0]
[1, 2, 3] [1, 1, 0]
[3, 2, 1] [0, 0, 0]
[-2, -3, -1] [2, 1, 0]
  • Solve Daily Temperatures with unresolved day indices. State why equal temperatures stay on the stack.
  • Solve Next Greater Element II for a circular input. Separate a second scan from the decision to add each original index.

Download the Python source to run the complete example locally.

Python’s stack tutorial defines append and pop at the list’s right end. These operations maintain the unresolved indices.

The USACO Guide’s nearest smaller element discussion presents the related problem of finding a smaller value to the left. Compare its removal condition with this lesson’s strictly greater value to the right.