← Quiz: Monotonic Stack: all 13 questions
Quiz: Monotonic Stack · Question 9 of 13
What does this print? (code)
What does this print?
a = [2, 1, 4, 3]
ans = [-1] * len(a)
stack = []
for i, x in enumerate(a):
while stack and a[stack[-1]] < x:
ans[stack.pop()] = x
stack.append(i)
print(ans, stack)
- A.[4, 4, -1, -1] []
- B.[1, 4, 3, -1] [3]
- C.[4, 4, -1, -1] [2, 3]
- D.[4, 4, 3, -1] [3]
Answer & explanation
Correct answer: [4, 4, -1, -1] [2, 3]
4 pops both 1 and 2. Indexes 2 and 3 (values 4 and 3) never meet a bigger value, so they stay on the stack with answer −1.
Can you get the rest right without peeking?
Take the timed Quiz: Monotonic Stack quiz free. Pass it to earn XP and count towards your certificate.
Start the quiz →