Monotonic Stack Finds Next Greater Elements

A monotonic stack of unresolved indices answers the next strictly larger value for every position in one linear pass instead of scanning right repeatedly.

PythonData Integrity

Code

pythonsnippet
19 lines
def next_greater(values):
    """For each index, the next value to its right that is strictly larger."""
    result = [-1] * len(values)
    # The stack stays monotonic: indices whose values still decrease.
    stack = []
    for i, value in enumerate(values):
        # A bigger value resolves every smaller value waiting on the stack.
        while stack and values[stack[-1]] < value:
            result[stack.pop()] = value
        stack.append(i)
    return result

prices = [4, 8, 5, 2, 9, 6]
print("prices :", prices)
print("greater:", next_greater(prices))

temps = [73, 74, 75, 71, 69, 72]
print("temps  :", temps)
print("greater:", next_greater(temps))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

prices : [4, 8, 5, 2, 9, 6]
greater: [8, 9, 9, 9, -1, -1]
temps  : [73, 74, 75, 71, 69, 72]
greater: [74, 75, -1, 72, 72, -1]

How it works

The moving parts are the function next_greater.

The file repeats itself only inside for i, value in enumerate(values).

Caveats

  • Entirely standard-library — copy it in and it runs.

Applying it

The primary signature is def next_greater(values)

Look for the prices :, greater:, temps : prefixes when the file runs; they tie each line to its step.

The surface worth importing is next_greater; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `next_greater` at load time.