ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Stack st = empty
for (each x in {3, 1, 4, 1, 5, 9, 2, 6})
    while (st not empty AND top(st) > x)
        pop(st)
    end while
    push(st, x)
end for
Print st from bottom to top
  1. A. 1 2 6
  2. B. 1 1 2 6
  3. C. 3 4 5 9 6
  4. D. 1 1 2 5 6

Correct answer: B. 1 1 2 6

This keeps a non-decreasing stack: 1 pops 3; the second 1 pops 4 (equal values stay); 2 pops 9 and 5. Final 1 1 2 6. Each element is pushed and popped at most once, so the loop is O(n) despite the nested while.

More Pseudocode and Code Tracing questions

Exams that ask this topic