🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← 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)
  1. A.[4, 4, -1, -1] []
  2. B.[1, 4, 3, -1] [3]
  3. C.[4, 4, -1, -1] [2, 3]
  4. 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 →