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 answerprint(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.
On a list that only goes down, no scan ever stops early. It compares about n²/2 pairs: O(n²).
A new value is the answer for every smaller value waiting on the stack
Turn it around. Instead of each item looking ahead for its answer, keep a stack of the items still waiting for one. When a new value arrives, it's the answer for every waiting item smaller than it. Those are all at the top of the stack, so pop them and record the answer. Then the new value starts waiting too.
In code, the stack waiting holds indices, and the answers start as a list of None. For each index i and its value v, a while loop pops every waiting index whose value is smaller than v, and records v as that index's answer. Then i goes on the stack. On [5, 3, 1, 4, 2, 6] that gives the same [6, 4, 4, 6, 6, None] as the scan.
Here is the waiting stack after each value:
The waiting stack after each value, top up
5
read 5
53
read 3
531
read 1
54
read 4popped 1 and 3: their answer is 4
542
read 2
6
read 6popped 2, 4 and 5: their answer is 6
Look at each column. The values waiting never go up from bottom to top, because anything smaller than a new arrival gets popped before the new one is pushed. A stack whose values only ever go one way is a monotonic stack, here one that never increases.
The stack holds indices, not values, so each answer can go into the right slot. The 5 waits until the 6. Anything still waiting at the end keeps None.
Some versions ask for a distance, not a value: how many days until a warmer day. In the editor, write steps_to_larger(values): for each item, how many places to the right the next larger value sits, or 0 when none does.
Pick an answer above to see the rest
Instructions
1
Write steps_to_larger(values): for each item, the distance to the next larger value on its right, or 0 when there is none. Keep a stack of the indices still waiting.