Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Insert words into a trie and count how many stored words start with a given prefix.

Problem: Insert words into a trie and count how many stored words start with a given prefix.
def make(words):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {'#': 0})
            node['#'] += 1
    return root
def count(root, p):
    node = root
    for ch in p:
        if ch not in node: return 0
        node = node[ch]
    return node['#']
t = make(["car", "card", "care", "cat", "dog", "do"])
print(count(t, "car"), count(t, "ca"), count(t, "do"), count(t, "cow"))
What is printed?
  1. A. 3 4 2 0
  2. B. 1 4 2 0
  3. C. 3 4 1 0
  4. D. 3 3 2 0

Correct answer: A. 3 4 2 0

Each node stores how many words pass through it. 'car' is a prefix of car, card, care; 'ca' adds cat; 'do' covers do and dog. Storing only an end-of-word flag would need a subtree walk to count. Insert and query are O(length).

More Coding Interview Problems questions

Exams that ask this topic