Data Structures & AlgorithmsModerateProduct Company SDE · trie round

Problem: Words apple, app, apt, bat, banana are stored in a trie that keeps a count of words passing through each node. What does the code print for prefixes 'ap', 'ban' and 'x'?

Problem: Words apple, app, apt, bat, banana are stored in a trie that keeps a count of words passing through each node. What does the code print for prefixes 'ap', 'ban' and 'x'?
words = ['apple', 'app', 'apt', 'bat', 'banana']
trie = {}
for w in words:
    node = trie
    for ch in w:
        node = node.setdefault(ch, {})
        node['#'] = node.get('#', 0) + 1
def cnt(p):
    node = trie
    for ch in p:
        if ch not in node:
            return 0
        node = node[ch]
    return node.get('#', 0)
print(cnt('ap'), cnt('ban'), cnt('x'))
What is printed?
  1. A. 2 1 0
  2. B. 3 2 0
  3. C. 3 1 1
  4. D. 3 1 0

Correct answer: D. 3 1 0

Prefix 'ap' is shared by apple, app and apt, prefix 'ban' only by banana, and 'x' by nothing. The count is stored at each node, so a prefix query is O(length).

More Coding Interview Problems questions

Exams that ask this topic