🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Tries (Prefix Trees): all 15 questions

Quiz: Tries (Prefix Trees) · Question 2 of 15

What does this print? (code)

What does this print?

root = {}
for w in ["to", "tea", "ten"]:
    node = root
    for ch in w:
        node = node.setdefault(ch, {})
    node["$"] = True

def count_nodes(n):
    return sum(1 + count_nodes(c) for k, c in n.items() if k != "$")

print(count_nodes(root))
  1. A.8
  2. B.6
  3. C.5
  4. D.3
Answer & explanation

Correct answer: 5

The nodes are t, o, e, a and n: "t" and "te" are shared, so 8 letters need only 5 nodes.

Can you get the rest right without peeking?

Take the timed Quiz: Tries (Prefix Trees) quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →