LearnQuestion bank

Implement a trie supporting insert, exact search and prefix counting, then add deletion. The code must run.

ResearchCodingMedium

Theme reported publicly: Google DeepMind

Answer it yourself first, out loud or on paper, then compare.

Answer

Model answer, written in a candidate's voice

In short

  • Clarify the API: insert, exact search, count_prefix (duplicates counted; the empty prefix counts every word), delete one occurrence returning a bool.
  • Node = dict of children + end counter + pass-through count; a dict suits any alphabet and sparse nodes, a 26-slot array is faster for lowercase ASCII but wastes memory.
  • Pass-through counts make count_prefix O(len(prefix)) with no subtree walk.
  • Delete: check existence, decrement counts on the way down, unlink the first child whose count reaches zero (pruning the rest of the path); shared prefixes such as ‘app’ inside ‘apple’ are never pruned.
  • Complexity: O(L) per operation, O(total characters) space.
  • Run tests: duplicates, empty string, missing word, deleting a prefix of another word, pruning.

In full

I would first pin down the API: insert(word); search(word) for exact matches; count_prefix(prefix), returning how many stored words start with the prefix, counting duplicates and counting every word for the empty prefix; and delete(word), removing one occurrence and returning whether anything was removed. Each node holds a dict of children, an end counter (how many copies of a word end here) and a pass-through count (how many stored words go through it). A dict handles any alphabet and only stores edges that exist; a fixed array of 26 slots is faster for lowercase ASCII but wastes memory on sparse nodes. Keeping a count on every node makes prefix counting O(len(prefix)) instead of a subtree walk. Delete first checks that the word exists, then walks down decrementing counts; as soon as a child’s count reaches zero, no other word uses that branch, so it is unlinked and the rest of the path is pruned in one step. Deleting a word that is a prefix of another (removing ‘app’ while ‘apple’ remains) only decrements counters and never prunes shared nodes.

class Node:
    __slots__ = ("children", "end", "count")

    def __init__(self):
        self.children = {}   # char -> Node; a dict handles any alphabet
        self.end = 0         # number of times a word ends here
        self.count = 0       # number of stored words passing through this node


class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word: str) -> None:
        node = self.root
        node.count += 1
        for ch in word:
            node = node.children.setdefault(ch, Node())
            node.count += 1
        node.end += 1

    def _find(self, s: str):
        node = self.root
        for ch in s:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word: str) -> bool:
        node = self._find(word)
        return node is not None and node.end > 0

    def count_prefix(self, prefix: str) -> int:
        node = self._find(prefix)
        return 0 if node is None else node.count

    def delete(self, word: str) -> bool:
        """Remove one occurrence of word; prune nodes no word passes through."""
        if not self.search(word):
            return False
        node = self.root
        node.count -= 1
        for ch in word:
            child = node.children[ch]
            child.count -= 1
            if child.count == 0:          # nothing else uses this branch
                del node.children[ch]
                return True
            node = child
        node.end -= 1
        return True


if __name__ == "__main__":
    t = Trie()
    for w in ["apple", "app", "apply", "bat", "app", ""]:
        t.insert(w)
    assert t.search("app") and t.search("apple") and t.search("")
    assert not t.search("ap") and not t.search("apples")
    assert t.count_prefix("app") == 4      # apple, app, app, apply
    assert t.count_prefix("") == 6         # every word, including ""
    assert t.count_prefix("b") == 1 and t.count_prefix("c") == 0
    assert t.delete("app") and t.search("app")      # one duplicate left
    assert t.delete("app") and not t.search("app")  # prefix of other words
    assert t.search("apple") and t.search("apply")  # longer words intact
    assert t.count_prefix("app") == 2
    assert t.delete("apple") and "e" not in t._find("appl").children  # pruned
    assert t.delete("bat") and "b" not in t.root.children
    assert not t.delete("bat") and not t.delete("zzz")
    assert t.delete("") and not t.search("") and t.count_prefix("") == 1
    print("all trie tests passed")

Complexity: insert, search, count_prefix and delete are each O(L) for a word or prefix of length L, with expected O(1) dict operations; space is O(total characters stored) in the worst case, with common prefixes shared. The tests cover duplicates, the empty string, a missing word, deleting a word that is a prefix of others, and pruning; running the file prints ‘all trie tests passed’.

Written by an independent AI reviewer.

What a strong answer covers

  • Clarify the API.
  • Choose the node structure (dict vs array children).
  • State complexity.
  • Run tests, including the empty string and deleting a prefix of another word.
  • Prune nodes on delete.

Common mistakes

  • Never running the code.
  • Missing edge cases.