Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← All patterns

    Tries

    A prefix tree: each edge is a character, so shared prefixes are stored once.

    Reach for it when

    • Prefix queries (startsWith, autocomplete)
    • Many words searched in a grid or a stream
    • Wildcard matching over a dictionary

    Core idea

    Each node holds a map from character to child plus an end-of-word flag. Insert and search cost O(length of word), independent of how many words are stored, and a DFS over the trie can prune an entire set of words the moment a prefix fails.

    Template · O(L) per operation, O(total characters) space

    class Trie:
    def __init__(self):
    self.root = {}
    def insert(self, word):
    node = self.root
    for ch in word:
    node = node.setdefault(ch, {})
    node["$"] = True # end of word
    def starts_with(self, prefix):
    node = self.root
    for ch in prefix:
    if ch not in node:
    return False
    node = node[ch]
    return True

    Common pitfalls

    • Forgetting the end-of-word marker (prefix vs word)
    • In Word Search II, remove found words to avoid duplicates

    Practice · 0 / 3 done