← Whiteboard questions

Implement Trie

Implement a trie (prefix tree) with insert and search

DSA, Medium, Tries

Which structure or algorithm, and what does it cost.

Build a class Trie that stores words made of lowercase letters. Store the words in a tree of letters (a trie), where words with the same start share nodes. A set of words plus a set of prefixes is not the method asked for. insert(word) adds a word. search(word) returns True only if that exact word was inserted before. starts_with(prefix) returns True if any inserted word begins with prefix. Inserting a word twice changes nothing. In the examples, the input is the list of operations in order. Each operation is a method name and its argument. The output is the list of results in the same order: None for insert, True or False for the other two.

Examples

Input ops = [["insert", "cart"], ["starts_with", "ca"], ["search", "car"], ["insert", "car"], ["search", "car"], ["search", "cartoon"]]
Output [None, True, False, None, True, False]
Why car is only a prefix of cart until it is inserted itself, so the first search for it fails and the second works. cartoon is longer than any stored word.
Input ops = [["search", "a"], ["starts_with", "a"], ["insert", "a"], ["starts_with", "ab"]]
Output [False, False, None, False]
Why nothing is stored at first, so both lookups fail. After a is inserted, ab still has no match.
Input ops = [["insert", "tea"], ["insert", "ten"], ["insert", "to"], ["starts_with", "te"], ["search", "te"], ["search", "ten"], ["search", "tens"]]
Output [None, None, None, True, False, True, False]
Why tea and ten share the start te, which is a prefix but not a word. A longer text such as tens is not stored.

Constraints

Your answer must contain

Target Aim for O(L) time per operation, where L is the length of the word or prefix.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Think of how a phone suggests words as you type. Words that start the same way share their first letters. Can you store those letters once?

Hint 2 the approach

Make a tree where each step down is one letter. A word is a path from the top. Think about how to mark where a word ends.

Hint 3 the key step

Search and starts_with take the same walk down the tree. At the end of the walk, what must search check that starts_with does not? Decide where insert leaves that mark.

Walkthrough

Full walkthrough brute force to best

Brute force

Keep every inserted word in a list. A search scans the list for an exact match. A prefix check scans the list and tests the start of each word. A search or a prefix check costs O(n * L) for n stored words of length up to L. An insert is one append. The list needs O(n * L) memory. With many words and many operations this is too slow.

Better method

Keep a set of whole words and a second set holding every prefix of every word. Now a search and a prefix check are each one set lookup, which hashes L letters, so O(L). Insert is slower: it builds and stores L prefixes, so O(L^2) time, and the shared letters are stored again in every prefix, so memory grows to O(n * L^2).

Best method

A trie stores each shared start only once. Every node holds a map from a letter to a child node, and a flag that says a word ends here. Insert walks the word from the top, creates any missing child, and sets the flag on the last node. To search, walk the letters: if a letter has no child, the answer is False. At the end of the word, the answer is the flag. A prefix check is the same walk, but it ignores the flag, because reaching the end of the prefix already means some word passes through that spot. This is correct because each path from the top spells exactly one text, so words with the same start share nodes, and the flag tells a stored word from a prefix. Each operation takes one step per letter.

Hand trace

Run on example 1. Insert cart: the trie is empty, so make nodes c, a, r, t and flag t. Starts_with ca: follow c, a, the path exists, so True. Search car: follow c, a, r, but r has no flag, so False. Insert car: all three nodes exist, so only r gets its flag. Search car: the path exists and r is flagged now, so True. Search cartoon: follow c, a, r, t, then there is no child o, so False. The result is [None, True, False, None, True, False].

Code

class Trie:
    def __init__(self):
        self.root = {}
    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True
    def _walk(self, text):
        node = self.root
        for ch in text:
            if ch not in node:
                return None
            node = node[ch]
        return node
    def search(self, word):
        node = self._walk(word)
        return node is not None and "$" in node
    def starts_with(self, prefix):
        return self._walk(prefix) is not None

Time and memory

O(L) time per operation, because each one takes one step per letter of the word or prefix. Memory is O(total letters stored) in the worst case, and less when words share starts.

Common mistakes

  • Returning True from search when the path exists but the end flag is not set. With cart stored, searching car must give False.
  • Setting the end flag on every node on the way, or forgetting to set it on the last node.
  • Treating a repeated insert as an error. It only sets a flag that may already be set.

Related problems

More Tries problems
Implement Trie: hints, walkthrough and Python solution