Skip to contentKEEP THE CRAFTTHE SANCTUARY

Trie

A trie shares character edges among words with common prefixes. Following a path proves prefix existence; a separate terminal marker proves a complete stored word. Insertions may create edges, while queries should only follow existing ones.

1 practice exercise4 interview problems

Recognize it when Repeated queries depend on prefixes or incremental character choices.

Checking your account…

Trie Code Labs

Mental Model

A trie stores one character per edge and shares nodes among words with the same prefix. Following the characters of a query reaches exactly its prefix node, if those edges exist.

Characters Label Edges

Represent each node as a dictionary from next character to child node. Insertion and lookup take O(L) expected time for a length-L string, independent of how many other words share the path. The dictionary contract(opens in a new tab) supplies expected constant-time edge lookup. Memory depends on stored characters and alphabet branching; sparse dictionaries avoid allocating a full alphabet array at every node.

Distinguish Prefix from Complete Word

Existing edges prove only that a prefix occurs. A terminal marker records that a stored word ends at this node, distinguishing app from the prefix of apple. The empty word, if allowed, marks the root terminal.

Separate Words from Prefixes

Reference
def trie_membership(words, queries):
    root = {}
    for word in words:
        node = root
        for character in word:
            node = node.setdefault(character, {})
        node[None] = True
    result = []
    for query in queries:
        node = root
        for character in query:
            if character not in node:
                node = None
                break
            node = node[character]
        result.append([node is not None and None in node, node is not None])
    return result
Practice

Implement trie_membership(words, queries). Return [is_word, is_prefix] for every query using explicit terminal markers.

Public tests

  • Verify word and prefix distinction

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Separate Words from Prefixes

def trie_membership(words, queries):
    root = {}
    for word in words:
        node = root
        for character in word:
            node = node.setdefault(character, {})
        node[None] = True
    result = []
    for query in queries:
        node = root
        for character in query:
            if character not in node:
                node = None
                break
            node = node[character]
        result.append([node is not None and None in node, node is not None])
    return result

Trace Prefix Paths and Terminal Membership Separately

Call the existing membership Lab with the empty word and ‘at’. The root itself is terminal for the empty query. The path for ‘a’ exists but is not terminal; only the next edge reaches the stored word ‘at’.

print(trie_membership(['', 'at'], ['', 'a', 'at', 'ax'])) followed by print(trie_membership([], ['']))

Step Executed statement State Why
1 node[None] = True empty word: root contains terminal key None The empty word ends at the root without a character edge.
2 node = node.setdefault(character, {}); node[None] = True word 'at': root -> 'a' -> 't'; terminal at 'at' Insertion creates two edges and marks only the completed word.
3 result.append([node is not None and None in node, node is not None]) query '': node = root; flags = [True, True] The empty path exists, and the inserted empty word supplies a terminal.
4 node = node[character]; result.append([node is not None and None in node, node is not None]) query 'a': path exists; no terminal; flags = [False, True] A proper prefix is not automatically a stored word.
5 node = node[character]; result.append([node is not None and None in node, node is not None]) query 'at': terminal reached; flags = [True, True] Complete traversal plus terminal proves word membership.
6 node = None; break query 'ax': missing 'x' edge; node = None The failed-edge branch leaves the character loop before result recording.
7 result.append([node is not None and None in node, node is not None]) query 'ax': flags = [False, False] The append runs after the character loop and uses the failed cursor for both answers.
Print Output
1 [[True, True], [False, True], [True, True], [False, False]]
2 [[False, True]]

Prefix and complete-word answers are intentionally separate. In this Lab, an empty query is a prefix even if no stored word exists because its path is the root; its is_word flag still depends on whether the empty word was inserted.

Measure Shared Prefixes

For autocomplete or pruning, follow edges until the first missing character. The number traversed is the longest stored prefix path; it does not imply a complete-word match.

Measure Trie Prefix Paths

Reference
def trie_prefix_match_lengths(words, queries):
    root = {}
    for word in words:
        node = root
        for character in word:
            node = node.setdefault(character, {})
    lengths = []
    for query in queries:
        node = root
        matched = 0
        for character in query:
            if character not in node:
                break
            node = node[character]
            matched += 1
        lengths.append(matched)
    return lengths
Practice

Implement trie_prefix_match_lengths(words, queries). Return the number of query characters whose edges exist from the root.

Public tests

  • Verify partial shared prefixes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Measure Trie Prefix Paths

def trie_prefix_match_lengths(words, queries):
    root = {}
    for word in words:
        node = root
        for character in word:
            node = node.setdefault(character, {})
    lengths = []
    for query in queries:
        node = root
        matched = 0
        for character in query:
            if character not in node:
                break
            node = node[character]
            matched += 1
        lengths.append(matched)
    return lengths

Choose Trie or Hash Set

Use a hash set for whole-word membership and a trie when prefixes, incremental character search, or dictionary-pruned backtracking dominate. Sorting strings can group prefixes compactly for offline work, while a trie supports repeated online queries.

Prefix and Terminal Marker Mistakes

  • Omitting the terminal marker makes every prefix look like a word.
  • Creating child dictionaries during a read mutates the trie unexpectedly.
  • Copying prefix strings at every DFS node can add quadratic work.
  • A fixed alphabet array wastes space when the character domain is large or sparse.

Explain It in an Interview

Define what a node and terminal marker mean, then charge work to query characters. State the alphabet assumption and why prefix existence differs from word existence.

Follow Trie Edges(opens in a new tab) isolates path traversal; Implement Trie(opens in a new tab) adds complete insert, search, and prefix APIs.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Trie (prefix tree)

Walk each char, create if missing, mark the end.

You store many words and ask about prefixes, or search many words in a grid at once.

Trigger words

  • word prefix
  • starts with
  • autocomplete
  • implement trie
  • many words in a grid
  • wildcard dot
class TrieNode:
    def __init__(self):
        self.children = {}      # letter -> TrieNode
        self.is_word = False

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

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

    def search(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.is_word

Spot it when

  • 'Implement trie', 'starts with', 'word search II'.
  • Wildcard search over a dictionary.

Remember

  • is_word marks where a complete word ends; a prefix may exist without being a word.
  • startsWith is search without the final is_word check.

How problems bend it

  • Wildcard '.': On '.', try every child recursively.
  • Word search II: Insert all words, then DFS the grid while walking down the trie.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Insert or query length L textO(L + 1)O((L + 1) * A)A maximum child-map width; ordinary hashing gives expected constant edge operations. Insertion may allocate L nodes; lookup uses constant cursor space.
Build and return q query resultsO(W + w + Q + q)O((W + w + Q + q) * max(1, A))W total stored word characters, w number of words, Q total query characters and q number of queries; empty words still incur one loop iteration, and the root always exists. Dictionary overhead and alphabet branching affect constants.

Space

O(L + 1) for insert or query length l text; O(W + q + 1) for build and return q query results.

Assumptions

  • A maximum child-map width; ordinary hashing gives expected constant edge operations. Insertion may allocate L nodes; lookup uses constant cursor space.
  • W total stored word characters, w number of words, Q total query characters and q number of queries; empty words still incur one loop iteration, and the root always exists. Dictionary overhead and alphabet branching affect constants.

Invariants Worth Saying Aloud

  1. After k characters, node represents exactly that query prefix.
  2. None terminal membership is separate from character-edge existence.
  3. A lookup stops at the first absent edge and does not add new child mappings.

When To Use Or Avoid Trie

Use It When

  • Use a trie for online prefix lookup or dictionary-constrained search.
  • Keep a terminal marker when complete-word membership differs from prefix membership.

Choose Another Tool When

  • Use a hash set when only whole-word membership matters.
  • Do not allocate a full alphabet array at every node for a large sparse character domain.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Accepting any existing prefix as a whole word

The path to 'a' can exist only because 'at' was inserted. A terminal marker is needed to distinguish complete words.

Prevent it: Test terminal membership after completing the query path.

Avoid

is_word = node is not None

Use instead

is_word = node is not None and None in node

Creating a missing edge during lookup

setdefault inserts a new child and turns a failed read into a mutation.

Prevent it: Use get or membership for queries; reserve setdefault for insertion.

Avoid

child = node.setdefault(character, {})

Use instead

child = node.get(character)

Checking an edge without moving the cursor

Leaving node at the root makes the next character lookup occur at the wrong prefix.

Prevent it: Advance to the child dictionary after a successful edge check.

Avoid

exists = character in node

Use instead

exists = character in node
if exists:
    node = node[character]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.