21/36
Part 6 of 8 · The monotonic stackLearn and do

A stack that stays in order: the monotonic stack

A new problem, and one more way to use a stack. For every value in a list, find the next value to its right that's larger, or None if there isn't one.

The obvious way scans ahead from each item until it finds something larger:

def next_larger_scan(values):
    answer = []
    for i, v in enumerate(values):
        found = None
        for w in values[i + 1:]:
            if w > v:
                found = w
                break
        answer.append(found)
    return answer


print(next_larger_scan([5, 3, 1, 4, 2, 6]))
Predict

For each of 5, 3, 1, 4, 2, 6, the next value to its right that's larger. What's the list?

Pick one to see what it prints.
Pick an answer above to see the rest