iq.lab
Python starts when a code cell comes near or you run one
09 Heaps and tries

Lesson 3 of 3

Tries

A trie stores words as paths of letters that hang from one root, so words that start alike share their first nodes. Insert, search and starts-with each walk one letter per step, and a wildcard search tries every branch, depth first.

About 1 hour 35 minutes, with the 2 problems worked in it
By the end you can
  • Draw the trie for a few words and count its nodes

  • Insert words into a dict-of-dicts trie, creating only the letters that are missing

  • Tell a whole-word search from a prefix check by the end-of-word mark

  • Write the same trie as a TrieNode class with children and is_end

  • Match a pattern with wildcard dots by trying every child, depth first

  • List every stored word that starts with a prefix

Your team's data catalog has a search box. Type ord and it offers orders, order_items and orders_daily: every table whose name starts with what you typed. It asks that question again at every keystroke, against tens of thousands of names.

A set answers the wrong question. "orders" in names finds a whole name with one hash lookup. But a set has no shortcut for "which names start with ord?". You have to ask every name, name.startswith("ord"), so each question costs one check per stored name. That is the brute force, and an interviewer expects you to name it first.

This lesson builds the structure made for prefix questions: the trie. Words that start alike share storage, so a prefix question follows one letter per step and never scans the stored words one by one.

A tree of letters

What shape lets "cat" and "car" share their first two letters? Store each word as a path down a tree, one letter per step. The top node is the root: it holds no letter and stands for the start, before any letter is read. Every other node holds one letter. A node's children are the nodes one step below it, one for each letter that can come next in some stored word. So a node can have many children, where a node in a binary tree or a heap has at most two.

The path root, c, a, t spells "cat", and the path root, c, a, r spells "car". Both paths run through the same nodes for c and a, so the shared start is stored once. This tree is a trie (the name comes from retrieval; most people say "try", so it does not sound like "tree"), also called a prefix tree.

A prefix of a word is a piece taken from its start: "c", "ca" and "cat" are prefixes of "cat". Every node stands for one prefix: the letters on the path from the root down to it. The root stands for the empty prefix, "", with no letters at all. "The node for 'ca'" means the node you reach by following c, then a.

A node also needs an end-of-word mark. Store "cart" alone, and the node for "car" exists, because "cart" passes through it. But "car" was never stored. So a node that exists proves only that some stored word starts that way, and each node carries a mark that says "a stored word ends here".

The widget below inserts four words one letter per step, then looks up the prefix "ca". The lime ring is the end-of-word mark. Above the drawing, a strip shows the word going in, with each letter tagged "new" (a node was added) or "reuse" (the node was already there). The readouts count letter nodes (the root is not counted), stored words, and the words that start with the prefix. The four words have 13 letters in all. Before you press Next, guess how many letter nodes they need.

Count the nodes yourself before we write any code.

Work it outCount the nodes

Insert "car", "card", "care" and "cat" into an empty trie, in that order. How many letter nodes does the trie have? Do not count the root. Type a whole number.

letter nodes

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Insert: follow the letters, add what is missing

How does a trie look in Python? Each node is a dict from a letter to the child node, and each child is another dict, so the whole trie is a dict of dicts. The root starts as an empty dict. The end mark is one more key, "$", with the value True. Any key that can never be a letter would do; $ means "end of the text" in regular expressions, so it reads as "end" at a glance. After inserting "cat" alone, the trie is {"c": {"a": {"t": {"$": True}}}}.

To insert a word, walk its letters from the root. For each letter, step down to that child, creating it first if it is missing. When the letters run out, put the end mark on the node you stand on. Before you step through, guess: once "cat" is in, how many new dicts does inserting "car" create?

Step throughBuilding a trie from nested dicts
Step 1 of 36
Line 1 is about to run.
def build(words):
root = {}
for word in words:
node = root
for ch in word:
if ch not in node:
node[ch] = {}
node = node[ch]
node["$"] = True
return root
Names
no names yet
Output
(nothing printed yet)

Insert never compares the new word with the stored ones. It does one dict check per letter and makes at most one new dict per letter, so inserting a word of L letters costs O(L), whether the trie holds 2 words or 2 million. Python's node = node.setdefault(ch, {}) does lines 6 to 8 in one line: setdefault returns the child for ch, adding an empty dict first if it is missing. Write the plain version until it comes without thinking.

Now read the nested dicts yourself. The second word here is shorter than the first.

PredictA word inside a word

This is the build function from the trace. Type exactly what the last line prints. Python prints a dict with single quotes, and a new key goes after the keys already in its dict.

def build(words):
    root = {}
    for word in words:
        node = root
        for ch in word:
            if ch not in node:
                node[ch] = {}
            node = node[ch]
        node["$"] = True
    return root

print(build(["tea", "te"]))

Search and starts-with: follow the letters

What can we ask once the words are in? Two questions, and one walk answers both. starts_with(prefix) asks whether some stored word begins with prefix. search(word) asks whether word itself was stored. Both follow the letters from the root, and a missing child ends the walk with no. If every letter is found, we stand on the node for the text. Then starts_with only needs that node to exist, and search also needs the end mark there.

The trace writes the walk once, as follow, which returns the node for a text, or None when a letter is missing. The trie is typed in directly this time; it holds "cat" and "car". Before you step through, guess the four values the two print lines show.

Step throughSearch versus starts-with
Step 1 of 58
Line 1 is about to run.
def follow(root, text):
node = root
for ch in text:
if ch not in node:
return None
node = node[ch]
return node
def starts_with(root, prefix):
return follow(root, prefix) is not None
def search(root, word):
node = follow(root, word)
return node is not None and "$" in node
root = {"c": {"a": {"t": {"$": True}, "r": {"$": True}}}}
print(starts_with(root, "ca"), search(root, "ca"))
print(search(root, "car"), starts_with(root, "cow"))
Names
no names yet
Output
(nothing printed yet)

The end mark is the whole difference between the two questions. The node for "ca" exists because two words pass through it, so the prefix check says yes. No word ends there, so the whole-word check says no. Leave the mark out and see what breaks:

Quick checkSearch without the end mark

A teammate leaves out the end mark and writes search with the follow function from the trace:

def search(root, word):
    return follow(root, word) is not None

The trie holds one word, "cart". What does search(root, "car") return?

Choose one answer, then check.

Here are the four answers for the trie and its three operations:

Recap: a trie stores each word as a path of letters from the root, sharing common starts. Insert creates the missing letters and marks the last node. Search and starts-with follow the letters and stop at a missing one. Starts-with needs only the node; search also needs the mark. Each costs O(L).

The same trie as a class

Why write a class, when nested dicts already work? The dict version mixes the end mark in with the letters. In the exercise above, the dict for "te" holds both 'a' and '$', so every loop over a node's keys has to remember to skip the mark. A small class gives the two parts their own names. The problems in this lesson use it:

class TrieNode:
    def __init__(self):
        self.children = {}    # letter -> TrieNode
        self.is_end = False   # True if a stored word ends here

As with ListNode in module 7, writing TrieNode() makes a new node and runs __init__ on it, with self naming that new node. children is the dict from before without the end mark, and is_end is the end mark. Every move of the dict version has a twin:

Dict of dictsTrieNode class
a new node: {}TrieNode()
ch not in nodech not in node.children
node = node[ch]node = node.children[ch]
node["$"] = Truenode.is_end = True
"$" in nodenode.is_end

Now put insert together in the class version. The lines are here, out of order.

Put in orderInsert, class version

Put the lines in order to build insert(root, word) for the class version. root is a TrieNode, and TrieNode is already defined:

class TrieNode:
    def __init__(self):
        self.children = {}    # letter -> TrieNode
        self.is_end = False   # True if a stored word ends here

Indentation is part of each line. Two lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • node = node.children[ch]
    • node.children[ch] = TrieNode()
    • def insert(root, word):
    • node = root
    • node.is_end = True
    • node = node.children[ch]
    • node.is_end = True
    • for ch in word:
    • if ch not in node.children:

    The problem wraps the root in a class Trie with insert, search and starts_with as methods. search and starts_with walk the same way, so write that walk once, as a helper method that returns the node for a text or None, and let both methods call it.

    mediumTrie (prefix tree)Design as coding target 25 min

    Build a prefix tree

    A prefix of a word is a piece taken from its start: "c", "ca", "car" and "cart" are the prefixes of "cart". Build a class Trie that stores words and answers two questions about them. Each call must take time that depends only on the length of its word or prefix, not on how many words are stored.

    • Trie() makes an empty store.
    • insert(word) stores word. Storing a word twice is the same as storing it once.
    • search(word) answers True exactly when word itself is one of the stored words. A prefix of a stored word does not count: after storing "cart", search("car") is False.
    • starts_with(prefix) answers True exactly when at least one stored word begins with prefix. A stored word begins with itself.

    Each Trie() you create starts empty and keeps its own words.

    Example 1
    Inputinsert("cat"), insert("car"), search("car"), search("ca"), starts_with("ca")OutputTrue, False, True

    These are the answers to the three questions, in order. "ca" begins both stored words, but it was never stored itself.

    Example 2
    Inputinsert("car"), search("cart"), starts_with("cart"), insert("cart"), search("cart"), search("car")OutputFalse, False, True, True

    Nothing stored begins with "cart" until it is inserted. Inserting "cart" keeps "car" stored.

    Example 3
    Inputinsert("go"), insert("go"), search("go"), starts_with("g"), search("g")OutputTrue, True, False

    Storing "go" twice changes nothing. "g" begins "go" but is not a stored word.

    Constraints
    • Every word and prefix has 1 to 2,000 lowercase English letters.

    • At most 3 × 104 calls in total.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The speed test is where the brute force falls over. It stores 14,000 words, then asks 14,000 prefix questions of 4 letters each. The trie follows at most 4 letters per question. The set version asks every stored word each time, and most questions find no match, so that comes to close to 200 million checks. Watch also for "team" then "tea": the second insert makes no node at all. It only sets is_end on a node that "team" already made.

    A dot matches any letter

    What if the search does not know every letter? The second problem stores words and checks patterns. A pattern is made of letters and dots, and a dot matches any one letter: "c.t" matches "cat" and "cot", but not "ct" or "cart". The whole stored word must match: same length, letter for letter.

    A letter has one child to follow. A dot could be any child, and we cannot tell in advance which one leads to a match. So we try them in turn: go down one child, and if the rest of the pattern fails below it, come back and try the next. This is depth-first search: go as deep as possible along one branch, then back up. Module 8 walked trees this way, and recursion keeps our place again: each call remembers which node it stands on and which pattern character comes next.

    matches(node, pattern, i) answers one question: can pattern[i:] be spelled starting below node, ending at a stored word? It has three cases:

    1. The pattern is used up (i == len(pattern)): the answer is whether a word ends at node.
    2. A letter: follow its one child, or return False if it is missing.
    3. A dot: try every child. Return True as soon as one child matches the rest, and return False only after every child has failed.

    The dot's loop is for letter, child in node.items():, which hands out each key of the dict with its value: a letter and its child node. In the dict version, the dot's loop must skip the "$" key, whose value is True, not a node. The trie below holds "cat" and "dog", and the pattern is "..g": two dots, then the letter g. The arrow under pattern shows i, the next character to match. Before you step through, guess which calls return False, and how many calls to matches run in all, counting the first one.

    Step throughA dot tries every child
    Step 1 of 42
    Line 1 is about to run.
    def matches(node, pattern, i):
    if i == len(pattern):
    return "$" in node
    ch = pattern[i]
    if ch == ".":
    for letter, child in node.items():
    if letter != "$" and matches(child, pattern, i + 1):
    return True
    return False
    if ch not in node:
    return False
    return matches(node[ch], pattern, i + 1)
    root = {"c": {"a": {"t": {"$": True}}}, "d": {"o": {"g": {"$": True}}}}
    Names
    no names yet
    Output
    (nothing printed yet)

    The early True and the late False are the whole algorithm, and the trace showed both. Returning True the moment one branch matches is safe, because one stored word is enough. Returning False is safe only after the loop ends, because a branch we have not tried yet may still match.

    One misplaced return turns this into a different algorithm. See what it does before you write the problem:

    Quick checkThe early return

    This version of the dot case returns inside the loop:

        if ch == ".":
            for letter, child in node.items():
                if letter != "$":
                    return matches(child, pattern, i + 1)
            return False

    The rest of matches is as in the trace. With the same trie ("cat" and "dog"), what does matches(root, ".og", 0) return?

    Choose one answer, then check.

    Now trace a pattern on paper, the way you would at a whiteboard with no run button.

    On paperTrace a pattern by hand

    The trie holds "bad", "bat" and "cab", inserted in that order. On paper, trace matches(root, ".a", 0) with the function from the trace. Write each call as the prefix of the node it stands on and its i, in the order the calls start. How many calls run in all, counting the first one? What does the first call return?

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    calls to matches

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The problem asks for the class version. There, node.children holds only letters, so the dot's loop needs no skip: it runs over node.children.values(), and the end check is node.is_end. You can also write matches inside search: then it reads pattern from there and needs only node and i.

    mediumTrie (prefix tree)Design as codingRecursion target 25 min

    Word store with wildcards

    Build a class WordDictionary that stores words and checks patterns against them. A pattern is made of lowercase letters and dots, and a dot matches any one letter: the pattern "c.t" matches "cat" and "cot", but not "ct" or "cart".

    • WordDictionary() makes an empty store.
    • add_word(word) stores word.
    • search(pattern) answers True exactly when at least one stored word matches pattern as a whole: the same length, with each letter equal and each dot standing for one letter.

    Each WordDictionary() you create starts empty and keeps its own words.

    Example 1
    Inputadd_word("cat"), add_word("cot"), add_word("dog"), search("c.t"), search("d.t"), search(".o."), search("..")OutputTrue, False, True, False

    "c.t" matches "cat". No stored word is d, any letter, t. ".o." matches "cot" and "dog". No stored word has two letters.

    Example 2
    Inputadd_word("map"), search("ma"), search("ma."), search("map.")OutputFalse, True, False

    A pattern must match a whole word: "ma" is too short and "map." is too long.

    Constraints
    • Every stored word has 1 to 25 lowercase English letters.

    • Every pattern has 1 to 25 characters, each a lowercase letter or a dot, with at most 2 dots.

    • At most 104 calls in total.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    Two things to keep from it. First, the problem's limit of 2 dots per pattern is what keeps the search fast: a search follows at most 26 × 26 = 676 paths, however many words are stored. Second, a dot never matches zero letters, because it always steps down to a child. With only "ab" stored, "ab." fails: the node for "ab" has no children, so the dot has nothing to try.

    The same depth-first walk answers the search box from the start of the lesson. To list every word with a given prefix, follow the prefix to its node. Then visit every node in the branch below it, the way a dot visits every child, and collect each word whose end you meet. Write it for the class version:

    Code itEvery word with a prefix

    Write words_with_prefix(root, prefix), which returns every stored word that starts with prefix, as a sorted list, or [] when there is none. A stored word starts with itself, and the empty prefix "" starts every word. The cell already has TrieNode and build(words), the class version of this lesson's insert: keep them as they are. Then press Watch it run.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Counting the words with a prefix needs no walk below it. Give each node a count, and let every insert add 1 to the count of each node on its path, the root included. Then the number of inserted words that start with a prefix is the count on the prefix's node: O(P) for a prefix of P letters. With "cat", "car" and "cart" inserted, the node for "ca" holds 3 and the node for "car" holds 2. If a word inserted twice should count once, call search first and skip the insert when the word is already stored.

    Recap: a dot is a choice, so the search becomes depth first: try each child, return True on the first match, and return False only when every child has failed. Collecting every word below a node is the same walk without the early stop. The practice bank's Word Search II (LeetCode 212, hard) combines a trie of many words with a walk over a grid of letters. Try it after module 10 has taught grids and module 11's Word Search has taught how to mark a cell on the way in and put it back on the way out.

    Last, say it the way you would in the room.

    Say itWhy not a set?

    The interviewer asks you to build a trie with insert, search and starts_with, then asks why you would not use a set of words. Write what you would say: the brute force first, then the walk, the notebook, the promise and the cost of the trie.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint