Data Structures & AlgorithmsModerateProduct Company SDE pattern

What is printed? (trie: count distinct prefixes / nodes)

What is printed? (trie: count distinct prefixes / nodes)
words = ["tea", "ten", "to", "inn", "in", "i"]
root, nodes = {}, 0
for w in words:
    t = root
    for ch in w:
        if ch not in t: t[ch] = {}; nodes += 1
        t = t[ch]
    t['$'] = True
print(nodes, len(root))
  1. A. 8 2
  2. B. 11 2
  3. C. 8 3
  4. D. 14 2

Correct answer: A. 8 2

Shared prefixes reuse nodes: tea adds t, e, a (3); ten adds only n (4); to adds o (5); inn adds i, n, n (8); in and i add nothing, they just mark existing nodes as word ends. The root has two children, t and i. 14 letters were inserted but only 8 nodes exist. Insert and search are O(word length).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic