Predict the output
What does this print?
vals = [4, 1, 3, 2, 5]
next_bigger = [-1] * len(vals)
stack: list[int] = []
for i, v in enumerate(vals):
while stack and vals[stack[-1]] < v:
next_bigger[stack.pop()] = v
stack.append(i)
print(next_bigger)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [5, 3, 5, 5, -1]
Right: each value's first bigger value to its right.
Items wait on the stack until something bigger arrives, which is when their answer is written.
Why not the others?
- B [5, 3, 5, 5, 5]. Nothing comes after 5, so it keeps -1.
- C [-1, 3, 5, 5, -1]. 4 is answered when 5 arrives.