ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
g = {1: [2, 3], 2: [4], 3: [], 4: []}
stack = [1]
out = []
while stack:
    u = stack.pop()
    out.append(u)
    stack.extend(g[u])
print(out)
  1. A. [1, 3, 2, 4]
  2. B. [1, 2, 4, 3]
  3. C. [1, 2, 3, 4]
  4. D. [1, 3, 4, 2]

Correct answer: A. [1, 3, 2, 4]

This is an iterative DFS. Pushing the children in list order means the last child is popped first, so 3 comes before 2. To mimic recursive preorder exactly, push children in reverse.

More Python Programming questions

Exams that ask this topic