ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
// a trie (prefix tree) starts with only an empty root
for each word in {"car", "cat", "cart", "dog", "do"}
    Node t = root
    for (each ch in word)
        if (t has no child ch)
            create child ch of t
            nodes = nodes + 1
        end if
        t = child ch of t
    end for
end for
Print nodes                    // nodes starts at 0
  1. A. 15
  2. B. 10
  3. C. 8
  4. D. 9

Correct answer: C. 8

Shared prefixes reuse nodes: car creates c, a, r (3); cat adds t (1); cart adds t under r (1); dog adds d, o, g (3); do adds nothing. nodes = 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic