Python 3D Academyবাংলা

Insert, search and starts-with

🌍 In real life. A word game checks two different things as you play. When you finish a word: "is cat a real word?" While you are still placing letters: "can ca still become a word?" If no word starts with what you have, there is no point going on.

A trie answers both with the same walk down the letters. The only difference is what you check when you get there: whether a word ends at that node (search), or just whether the node exists at all (starts-with).

The idea in one sentence: to search for a word or check a prefix, walk down from the root one letter at a time; if a letter is missing, the answer is no; if you reach the end, search also needs the end flag, while starts-with only needs the node.

Its words:

  • search(word): True only if exactly this word was inserted
  • starts_with(prefix): True if any inserted word begins with these letters
  • walk: following the letters down from the root, stopping at the first missing one
  • collect: gathering every word end below a node, for autocomplete

How it works, step by step:

  1. start at the root
  2. for each letter: if the node has no child for it, stop: no word continues this way
  3. otherwise step down into that child
  4. at the end: search returns the end flag; starts-with returns True

Watch three questions on the same trie: ca is only a prefix, cow falls off after c, and four words start with ca:

Why it is correct. A word is in the trie exactly when its letters form a path from the root and the last node is flagged, because insert made that path and set that flag, and nothing else does. A missing letter means no inserted word has that prefix, since every inserted word's prefixes all exist as nodes. So stopping there is safe. For autocomplete, the words that start with p are exactly the word ends in the subtree under p's node, and visiting the children in letter order lists them alphabetically.

What it costs, by counting. search and starts_with take at most L steps for L letters: O(L), however many words are stored. A Python set also checks a whole word in O(L) on average, by hashing it (Chapter 35), but it can't answer starts-with without looking at every word: n words of length L cost O(n × L). Autocomplete costs O(L) to reach the prefix plus the size of the subtree below it, the part that holds the answers.

class TrieNode:
    def __init__(self):
        self.children = {}               # letter -> TrieNode
        self.is_end = False              # does a word end here?

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

    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_end = True

    def _walk(self, letters):         # the node at the end of the path, or None
        node = self.root
        for ch in letters:
            if ch not in node.children:
                return None
            node = node.children[ch]
        return node

    def search(self, word):
        node = self._walk(word)
        return node is not None and node.is_end   # the whole word, not just a start

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

t = Trie()
for word in ["car", "cart", "care", "cat", "dog"]:
    t.insert(word)
print(t.search("cat"), t.search("ca"), t.search("cow"))
print(t.starts_with("ca"), t.starts_with("do"), t.starts_with("x"))

Mistakes and edge cases.

  • search that forgets the end flag: it returns True for "ca", which is only the start of other words
  • node.children[ch] without checking: a missing letter raises KeyError; check with in (or use .get) and stop
  • the empty string: starts_with("") is True (every word starts with nothing), while search("") is True only if "" was inserted
  • autocomplete order: a Python dict keeps letters in the order they were added, not alphabetical; sort the children if the order matters
  • inserting the same word twice: harmless; the path exists and the flag is already set

Quiz

  1. What does this print?

    class TrieNode:
        def __init__(self):
            self.children = {}               # letter -> TrieNode
            self.is_end = False              # does a word end here?
    
    class Trie:
        def __init__(self):
            self.root = TrieNode()
    
        def insert(self, word):
            node = self.root
            for ch in word:
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.is_end = True
    
        def _walk(self, letters):         # the node at the end of the path, or None
            node = self.root
            for ch in letters:
                if ch not in node.children:
                    return None
                node = node.children[ch]
            return node
    
        def search(self, word):
            node = self._walk(word)
            return node is not None and node.is_end   # the whole word, not just a start
    
        def starts_with(self, prefix):
            return self._walk(prefix) is not None
    
    t = Trie()
    for word in ["sea", "seat", "tea"]:
        t.insert(word)
    print(t.search("sea"), t.search("se"), t.starts_with("se"), t.starts_with("te"), t.search("tea"))
  2. search("ca") returns True although only car and cat were inserted. Which line is wrong?

    def search(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return True
  3. Why can a trie answer starts_with quickly when a set can't?

    • In a trie, all words with the same start share one node; a set keeps every word separately, so it must check them all
    • Sets can't hold strings
    • Tries keep fewer words
  4. Autocomplete for ca. What does this print?

    class TrieNode:
        def __init__(self):
            self.children = {}               # letter -> TrieNode
            self.is_end = False              # does a word end here?
    
    def autocomplete(words, prefix):
        root = TrieNode()
        for word in words:
            node = root
            for ch in word:
                node = node.children.setdefault(ch, TrieNode())
            node.is_end = True
        node = root
        for ch in prefix:                    # walk down to the prefix's node
            if ch not in node.children:
                return []
            node = node.children[ch]
        found = []
        def collect(node, word):             # every word end below it, letters in order
            if node.is_end:
                found.append(word)
            for ch in sorted(node.children):
                collect(node.children[ch], word + ch)
        collect(node, prefix)
        return found
    
    print(autocomplete(["cat", "dog", "car", "cart", "cab"], "ca"))
    print(autocomplete(["cat"], "co"))
  5. A trie holds a million words. How long does search("zebra") take?

    • At most 5 steps, one per letter
    • About 20 steps, log₂ of a million
    • Up to a million steps

Coding tasks

  1. Write the class Trie with insert(word), search(word) (True only for a whole inserted word) and starts_with(prefix) (True if any inserted word starts with it). The TrieNode class is given.

  2. Write autocomplete(words, prefix): every word in words that starts with prefix, in alphabetical order. Build a trie, walk to the prefix's node, and collect the word ends below it, taking the children in letter order.