22/36
Part 6 of 8 · The monotonic stackLearn and do
Each index is pushed once and popped at most once, so the pass is O(n)
The while inside the for can pop several items at once: the 6 popped three. But every index is pushed once and popped at most once. So across the whole run, the pops add up to at most n. Here it was 6 pushes and 5 pops.
That's O(n) time, and O(n) memory for the stack and the answer. Measured on lists that only go down, best of 3 runs or more:
| n | next_larger_scan | The waiting stack |
|---|---|---|
| 1,000 | 5.2 ms | 0.046 ms |
| 2,000 | 21.4 ms | 0.090 ms |
| 4,000 | 86.8 ms | 0.182 ms |
| 8,000 | 355.3 ms | 0.374 ms |
The scan grows four times when n doubles, and the stack two times. At 8,000 items the stack is about 950 times faster.
In the editor, finish next_larger_counted(values): the next larger value for each item, found with the waiting stack, plus a count of every comparison the while makes. The count stays under 2n.