Stacks and queues · stretch
Next greater number
Write next_greater(nums) returning a list where each position holds the first number to its right that is bigger, or -1 if there is none. [2, 1, 3] gives [3, 3, -1].
Keep a stack of positions still waiting for their answer. Each new number answers every waiting position smaller than it.
- right answers
- arguments left as they should be
- fast enough at scale
Run adds print(next_greater([2, 1, 3])) after your code, to try it.
Stuck on the idea rather than the code? The Waiting in a stack, waiting in a queue lesson walks through it.