Tries

Phase 2 4 solutions

Tries

mindmap
  root((Tries))
    Basic Trie
      Implement Trie Prefix Tree LC208
    Wildcard Search
      Design Add And Search Words LC211
    Trie + DP
      Extra Characters in a String LC2707
    Trie + Backtracking
      Word Search II LC212

Problem List

# Problem LC Difficulty
1 Implement Trie Prefix Tree 208 🟑 Medium
2 Design Add And Search Words 211 🟑 Medium
3 Extra Characters in a String 2707 🟑 Medium
4 Word Search II 212 πŸ”΄ Hard

Approach Diagrams

Trie Node Structure

flowchart TD
    A["TrieNode ───────────── children: dict[char β†’ TrieNode] is_end: bool"] --> B["Example: insert 'cat'"]
    B --> C["root  children: c β†’ ..."]
    C --> D["c-node  children: a β†’ ..."]
    D --> E["a-node  children: t β†’ ..."]
    E --> F["t-node  is_end = True"]

Insert / Search / StartsWith Operations

flowchart TD
    A[Operation] --> B{"Type"}
    B -- insert word --> C[node = root]
    C --> D[For each char in word]
    D --> E{"char in node.children?"}
    E -- No --> F[Create new TrieNode]
    E -- Yes --> G[Move to child]
    F --> G
    G --> D
    D --> H[Mark last node is_end = True]
    B -- search word --> I[node = root]
    I --> J[For each char in word]
    J --> K{"char in node.children?"}
    K -- No --> L[Return False]
    K -- Yes --> M[Move to child]
    M --> J
    J --> N[Return node.is_end]
    B -- startsWith prefix --> O[Same as search but return True if all chars found]

Wildcard Search with DFS β€” LC 211

flowchart TD
    A[search word with dots] --> B[DFS from root]
    B --> C[For each char in word]
    C --> D{"char == dot?"}
    D -- Yes --> E[Recurse into ALL children nodes]
    D -- No --> F{"char in node.children?"}
    F -- No --> G[Return False]
    F -- Yes --> H[Move to child]
    E --> I{"Any child returns True?"}
    I -- Yes --> J[Return True]
    I -- No --> G
    H --> C
    C --> K[Return node.is_end]

Trie + Backtracking β€” Word Search II (LC 212)

flowchart TD
    A[Build Trie from word list] --> B[DFS on each board cell]
    B --> C{"char at cell in trie node children?"}
    C -- No --> D[Prune: return early]
    C -- Yes --> E[Move to trie child node]
    E --> F{"node.is_end?"}
    F -- Yes --> G[Add word to results mark node.is_end = False to avoid duplicates]
    F -- No --> H[Continue DFS]
    G --> H
    H --> I[Mark cell visited explore 4 neighbors]
    I --> J[Unmark cell backtrack]
    J --> K{"Trie node has no children left?"}
    K -- Yes --> L[Prune trie branch for efficiency]
    K -- No --> B

When to Use Trie vs HashMap

flowchart TD
    A[String lookup problem] --> B{"Need prefix operations?"}
    B -- Yes --> C{"How many words?"}
    C -- Many, shared prefixes --> D[Trie space-efficient LC 208, 211, 212]
    C -- Few words --> E[HashSet is fine]
    B -- No --> F{"Exact match only?"}
    F -- Yes --> G["HashMap / HashSet simpler, O1 lookup"]
    F -- No, need wildcard --> H[Trie + DFS LC 211]
    A --> I{"Need to find all words in a grid?"}
    I -- Yes --> J[Trie + Backtracking LC 212 better than running search per word]
    A --> K{"DP with word boundary checks?"}
    K -- Yes --> L[Trie speeds up boundary lookup LC 2707]

Complexity Summary

Problem Time Space Notes
Insert (208) O(L) O(L) L = word length
Search (208) O(L) O(1)
StartsWith (208) O(L) O(1)
Add & Search (211) O(L) insert, O(26^L) search worst O(total chars) Dot triggers full DFS
Extra Characters (2707) O(nΒ² Β· L) O(total chars) DP + trie lookup
Word Search II (212) O(mΒ·n Β· 4^L) O(total chars) Trie prunes repeated searches

L = average word length, mΒ·n = board size


Study Order

flowchart LR
    S1["Step 1 Implement Trie 208 Build the data structure"]
    S2["Step 2 Add & Search Words 211 Add wildcard DFS"]
    S3["Step 3 Extra Characters 2707 Trie + DP"]
    S4["Step 4 Word Search II 212 Trie + Backtracking"]
    S1 --> S2 --> S3 --> S4

Key insight: A Trie is just a tree where each edge is a character. Its power is shared prefixes β€” instead of storing "cat", "car", "card" three times, they share the "ca" path. Always implement LC 208 from scratch before attempting the others.

Tries (Prefix Trees)

Core Intuition

A trie stores strings character by character in a tree. Each node represents a prefix. Use when you need fast prefix lookups, autocomplete, or searching a dictionary of words.

  • TrieNode: children map (dict or array[26]) + is_end flag
  • Insert: Walk/create nodes for each character β€” O(m) where m = word length
  • Search: Walk nodes; check is_end at last char β€” O(m)
  • StartsWith: Same as search but do not require is_end β€” O(m)
  • Wildcard: DFS with branching on . nodes β€” O(26^m) worst case (all dots)
  • Trie + Backtracking: Build trie from word list, then DFS grid β€” prune when current trie node is None

When Trie beats HashMap:

  • Prefix queries: HashMap cannot enumerate all strings with a given prefix without scanning all keys
  • Wildcard matching: . expansion fans out over trie children naturally; set lookup cannot do this
  • Shared prefix storage: "apple" and "application" share 5 nodes β€” saves space and allows early termination

Three core operations β€” all O(m) in word length m:

  • insert(word): walk and create nodes; set is_end = True on last node
  • search(word): walk nodes; return node.is_end at end, False if any node missing
  • startsWith(prefix): walk nodes; return True if all nodes exist, end flag irrelevant

Trie + Backtracking (word_search_ii):

  • Build trie from word list once; then DFS the board tracking the current trie node
  • If node.children[ch] is None, prune the entire DFS branch immediately
  • After finding a word, set node.word = None to mark used β€” avoids duplicate results
  • Optionally remove childless nodes bottom-up to shrink the trie during search

Trie + DP (extra_characters_in_a_string):

  • dp[i] = minimum extra characters in s[0..i-1]
  • At each position i, start a trie walk from position j to i; if trie marks a word end, update dp[i] = min(dp[i], dp[j])
  • Trie walk from j allows early exit when no dictionary word starts with the current prefix β€” O(n * m) vs O(n^2) set scan in theory

Suffix Trie vs Prefix Trie:

  • All four problems here use a prefix trie (insert left-to-right)
  • Suffix tries/suffix arrays handle substring queries (does s contain t anywhere?) β€” different beast

Java Idioms

TrieNode Structure

Define as an inner class or package-private class. Use a fixed 26-element array for lowercase-only problems β€” faster than HashMap (no hashing, no boxing, cache-friendly):

class TrieNode {
    TrieNode[] children = new TrieNode[26];
    boolean isEnd;
}

For problems with arbitrary characters or Unicode, swap TrieNode[26] for HashMap<Character, TrieNode>.

Indexing

int idx = c - 'a';  // 'a' -> 0, 'z' -> 25

Insert Loop (common mistake vs correct form)

Wrong β€” does not store the new node back into the parent:

// BUG: node.children[idx] is still null after this
if (node.children[idx] == null) new TrieNode();  // node lost
node = node.children[idx];                        // NullPointerException

Correct:

for (char c : word.toCharArray()) {
    int idx = c - 'a';
    if (node.children[idx] == null) {
        node.children[idx] = new TrieNode();  // assign back into parent
    }
    node = node.children[idx];
}
node.isEnd = true;

Wildcard Search (design_add_and_search_words)

Iterative search cannot branch on . cleanly. Use a recursive DFS helper:

private boolean dfs(TrieNode node, String word, int i) {
    if (i == word.length()) return node.isEnd;
    char c = word.charAt(i);
    if (c == '.') {
        for (TrieNode child : node.children) {
            if (child != null && dfs(child, word, i + 1)) return true;
        }
        return false;
    }
    TrieNode next = node.children[c - 'a'];
    return next != null && dfs(next, word, i + 1);
}

Word Search II (board DFS)

Build trie from word list, then DFS from each cell. Mark visited cells in-place:

board[r][c] = '#';   // mark visited
// ... recurse into 4 neighbors, passing current trie node's child ...
board[r][c] = tmp;   // restore

Check node.word != null (or node.isEnd) to add to result; set node.word = null after adding to prevent duplicates.

Extra Characters β€” Trie + DP

// dp[i] = min extra chars in s[0..i-1]; dp[0] = 0
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
    dp[i] = dp[i - 1] + 1;  // default: s[i-1] is an extra char
    TrieNode node = root;
    for (int j = i - 1; j >= 0; j--) {
        int idx = s.charAt(j) - 'a';
        if (node.children[idx] == null) break;  // no word starts here, prune
        node = node.children[idx];
        if (node.isEnd && dp[j] != Integer.MAX_VALUE) {
            dp[i] = Math.min(dp[i], dp[j]);
        }
    }
}
return dp[n];

Problems

Problem Key Insight Tricky Part Common Mistakes Time Space
Implement Trie (LC 208, Medium) TrieNode with children dict/array and is_end flag; three operations walk the same path search vs startsWith: both walk identically but only search checks is_end Using a flat dict of full strings β€” defeats prefix sharing; not marking is_end on insert O(m) per operation O(n * m) total nodes
Add and Search Words (LC 211, Medium) Standard trie insert; search uses recursive DFS β€” on ., branch into all non-null children . forces recursion; iterative approach with a queue works but is messier; must handle . at end of pattern Trying iterative search and getting stuck on branching; forgetting that . can match zero chars does not apply β€” it matches exactly one O(m) insert, O(26^m) worst-case search O(n * m) nodes
Extra Characters in a String (LC 2707, Medium) dp[i] = min extra chars in s[0..i-1]; for each i walk trie backwards from i to find words ending at i Walk trie from j going left-to-right through s[j..i-1] β€” direction matters; inner loop iterates j from i-1 down to 0 Not initializing dp[0] = 0; scanning with set instead of trie (both work, trie prunes earlier); off-by-one on dp indices O(n^2) with trie walk O(n + d * m) where d = dict size, m = avg word length
Word Search II (LC 212, Hard) Build trie from all words once; DFS board tracking current trie node; prune when node has no child for current char In-place board marking (board[r][c] = '#') for visited; restore after DFS; after finding word set node.word = None to skip duplicates Running separate Word Search I per word β€” O(words * m * n * 4^L); forgetting to restore board cell; adding duplicate words when word appears multiple times in grid O(m * n * 4 * 3^(L-1)) DFS O(total chars in words) for trie

Edge Cases

  1. Empty string insert/search: An empty word terminates immediately; is_end must be set on the root node itself. Check that insert and search both handle len(word) == 0 β€” root's is_end is set after the (empty) loop.

  2. Prefix searched as full word (search vs startsWith): Inserting "apple" then searching "app" must return False. The trie path exists but is_end is not set at the "p" node. A common bug is returning True whenever the path exists.

  3. Wildcard . at end of pattern: Pattern "ab." must match any three-letter word starting with "ab". The . still consumes exactly one character β€” it does not match zero. The DFS base case i == word.length() handles this correctly only if the last . has already advanced i.

  4. Duplicate words in word list (word_search_ii): The problem states all words are unique, but a defensive implementation sets node.word = None after collecting a word. Without this, the same word could be added to the result multiple times if multiple DFS paths reach the same trie node.

  5. Very long words: Trie depth equals the maximum word length. A trie holding one 2000-character word has 2000 nodes in a single chain. This is correct but means the DFS in word_search_ii recurses to depth L, not depth of the board.

  6. startsWith vs search confusion: startsWith("app") must return True even if "app" was never inserted β€” only "apple" was. The difference is solely the is_end check at the end. Mixing up the return value of the two methods is the single most common bug in LC 208.

  7. Word is a prefix of another word in dictionary: Inserting "app" then "apple" β€” the node for "app" must have is_end = True and also have a child "l". Both can be true simultaneously. A node's is_end flag is independent of whether it has children.

  8. No dictionary match (extra_characters): If no word in the dictionary matches any substring of s, then dp[i] = i for all i β€” every character is extra. The transition dp[i] = dp[i-1] + 1 (default skip) handles this automatically as long as dp[0] = 0.


General Notes

  • For lowercase-only problems (all four here), prefer children = [None] * 26 / TrieNode[26] over a dict β€” O(1) indexed access, better cache behavior, no hash overhead.
  • The DFS in word_search_ii prunes on node = node.children.get(ch) returning None β€” this is where the trie pays off vs brute force.
  • Trie + DP (extra_characters) is a template for any "segment string using a dictionary" DP problem.
  • When inserting into a trie in Java, always assign the new node back to parent.children[idx] before advancing node β€” forgetting the assignment is the #1 Java trie bug.
# Problem LC Difficulty
1 Implement Trie Prefix Tree 208 🟑 Medium
2 Design Add And Search Words 211 🟑 Medium
3 Extra Characters in a String 2707 🟑 Medium
4 Word Search II 212 πŸ”΄ Hard
Design Add And Search Words PythonJava
β–Ό
"""
# 211: Design Add and Search Words Data Structure

Design a data structure that supports adding new words and finding whether a
string matches any previously added string, where the search word may contain
`'.'` wildcards that each match any single letter.

## Examples
```text
Input:  addWord("bad"); addWord("dad"); addWord("mad")
        search("pad"); search("bad"); search(".ad"); search("b..")
Output: False; True; True; True
```

## Constraints
- 1 <= word.length <= 25
- Words in addWord consist of lowercase English letters.
- Words in search consist of '.' or lowercase English letters.
- At most 10^4 calls to addWord and search.
"""
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False


class WordDictionary:
    """
    **LC 211: Design Add and Search Words Data Structure**

    Design a data structure that supports adding new words and finding if a
    string matches any previously added string. The search word can contain
    dots `'.'` where each dot can match any letter.

    * `WordDictionary()` β€” Initializes the object.
    * `addWord(word)` β€” Adds `word` to the data structure.
    * `search(word)` β€” Returns `true` if any string matches `word`.
      A `'.'` matches any single character.

    Example 1:
    ```text
    Input:  ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
            [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
    Output: [null,null,null,null,false,true,true,true]
    ```

    **Constraints:**
    * `1 <= word.length <= 25`
    * `word` in `addWord` consists of lowercase English letters
    * `word` in `search` consists of `'.'` or lowercase English letters
    * At most `10^4` calls to `addWord` and `search`
    """

    def __init__(self):
        # O(1)
        pass

    def addWord(self, word: str) -> None:
        # Standard trie insert: create nodes as needed, mark end_of_word
        # O(m) where m = len(word)
        pass

    def search(self, word: str) -> bool:
        # DFS through trie; '.' matches any child node (try all branches)
        # Regular char must match exactly; return True if end_of_word reached
        # O(m * 26^d) where d = number of dots, worst case O(m * 26^m)
        pass


if __name__ == "__main__":
    wd = WordDictionary()
    wd.addWord("bad")
    wd.addWord("dad")
    wd.addWord("mad")
    print(wd.search("pad"))   # Expected: False
    print(wd.search("bad"))   # Expected: True
    print(wd.search(".ad"))   # Expected: True
    print(wd.search("b.."))   # Expected: True
Extra Characters In A String PythonJava
β–Ό
from typing import List


class Solution:
    """
    **LC 2707: Extra Characters in a String**

    You are given a string `s` and a dictionary of words `dictionary`. Break `s`
    into one or more non-overlapping substrings such that each substring is in
    the dictionary. Some characters may be left over β€” return the **minimum**
    number of extra characters left over.

    Example 1:
    ```text
    Input:  s = "leetscode", dictionary = ["leet","code","leetcode"]
    Output: 1
    Explanation: Break into "leet" + "s" + "code". Extra = 1 character "s".
    ```

    Example 2:
    ```text
    Input:  s = "sayhelloworld", dictionary = ["hello","world"]
    Output: 3
    Explanation: Break into "say" + "hello" + "world". Extra = 3 characters "say".
    ```

    **Constraints:**
    * `1 <= s.length <= 50`
    * `1 <= dictionary.length <= 50`
    * `1 <= dictionary[i].length <= 50`
    * `dictionary[i]` and `s` consist of only lowercase English letters
    """

    def minExtraChar_dp(self, s: str, dictionary: List[str]) -> int:
        # O(n^2 * m) β€” DP with hash set lookup
        pass

    def minExtraChar(self, s: str, dictionary: List[str]) -> int:
        # DP: dp[i] = min extra chars in s[:i]
        # For each position, try all dictionary words ending at i; take minimum
        # O(n^2 * m) β€” DP with Trie for prefix matching
        pass


if __name__ == "__main__":
    sol = Solution()

    # Example 1: expected 1
    print(sol.minExtraChar("leetscode", ["leet", "code", "leetcode"]))

    # Example 2: expected 3
    print(sol.minExtraChar("sayhelloworld", ["hello", "world"]))
Implement Trie Prefix Tree PythonJava
β–Ό
"""
# 208: Implement Trie (Prefix Tree)

Implement a trie (prefix tree) supporting insertion, exact-match search, and
prefix search: `insert(word)`, `search(word)`, and `startsWith(prefix)`.

## Examples
```text
Input:  insert("apple"); search("apple"); search("app")
        startsWith("app"); insert("app"); search("app")
Output: True; False; True; True
```

## Constraints
- 1 <= word.length, prefix.length <= 2000
- word and prefix consist only of lowercase English letters.
- At most 3 * 10^4 calls in total.
"""
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False


class Trie:
    """
    **LC 208: Implement Trie (Prefix Tree)**

    A trie (prefix tree) is a tree data structure used to efficiently store
    and retrieve keys in a dataset of strings. Implement the `Trie` class:

    * `Trie()` β€” Initializes the trie object.
    * `insert(word)` β€” Inserts the string `word` into the trie.
    * `search(word)` β€” Returns `true` if `word` is in the trie (exact match).
    * `startsWith(prefix)` β€” Returns `true` if any previously inserted string
      has the prefix `prefix`.

    Example 1:
    ```text
    Input:  ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
            [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
    Output: [null, null, true, false, true, null, true]
    ```

    **Constraints:**
    * `1 <= word.length, prefix.length <= 2000`
    * `word` and `prefix` consist only of lowercase English letters
    * At most `3 * 10^4` calls in total
    """

    def __init__(self):
        # O(1)
        pass

    def insert(self, word: str) -> None:
        # Walk character by character; create new TrieNode if path doesn't exist
        # Mark end_of_word on the final node
        # O(m) where m = len(word)
        pass

    def search(self, word: str) -> bool:
        # Walk the trie; return True only if path exists AND end_of_word is set
        # O(m)
        pass

    def startsWith(self, prefix: str) -> bool:
        # Walk the trie; return True if the prefix path exists (end_of_word irrelevant)
        # O(m)
        pass


if __name__ == "__main__":
    trie = Trie()
    trie.insert("apple")
    print(trie.search("apple"))       # Expected: True
    print(trie.search("app"))         # Expected: False
    print(trie.startsWith("app"))     # Expected: True
    trie.insert("app")
    print(trie.search("app"))         # Expected: True
Word Search Ii PythonJava
β–Ό
"""
# 212: Word Search II

Given an `m x n` board of characters and a list of `words`, return all words
that can be constructed from sequentially adjacent (horizontal/vertical) cells,
using each cell at most once per word.

## Examples
```text
Input:  board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
        words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]

Input:  board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
```

## Constraints
- m == board.length, n == board[i].length
- 1 <= m, n <= 12
- 1 <= words.length <= 3 * 10^4
- 1 <= words[i].length <= 10
- All strings in words are unique.
"""
from typing import List


class TrieNode:
    def __init__(self):
        self.children = {}
        self.word = None


class Solution:
    """
    **LC 212: Word Search II**

    Given an `m x n` board of characters and a list of strings `words`, return
    all words on the board. Each word must be constructed from letters of
    sequentially adjacent cells (horizontally or vertically neighboring). The
    same cell may not be used more than once in a word.

    Example 1:
    ```text
    Input:  board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
            words = ["oath","pea","eat","rain"]
    Output: ["eat","oath"]
    ```

    Example 2:
    ```text
    Input:  board = [["a","b"],["c","d"]]
            words = ["abcb"]
    Output: []
    ```

    **Constraints:**
    * `m == board.length`, `n == board[i].length`
    * `1 <= m, n <= 12`
    * `board[i][j]` is a lowercase English letter
    * `1 <= words.length <= 3 * 10^4`
    * `1 <= words[i].length <= 10`
    * All strings in `words` are unique
    """

    def findWords_brute(self, board: List[List[str]], words: List[str]) -> List[str]:
        # O(w * m * n * 4^L) β€” DFS per word independently
        pass

    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        # Build a trie from all words for efficient prefix pruning
        # DFS from each cell; prune when current path is not a trie prefix
        # When a word is found in trie, add to result and remove from trie to avoid duplicates
        # O(m * n * 4^L) β€” Trie + backtracking DFS (prune branches)
        pass


if __name__ == "__main__":
    sol = Solution()

    # Example 1: expected ["eat", "oath"]
    board1 = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]]
    print(sol.findWords(board1, ["oath","pea","eat","rain"]))

    # Example 2: expected []
    board2 = [["a","b"],["c","d"]]
    print(sol.findWords(board2, ["abcb"]))

Trie β€” Insert & Search

Prefix tree for O(m) string operations. * = end of word.

root
  • a
    • p
      • p *
        • l
          • e *
      • t *
  • b
    • a
      • l
        • l *
      • t *
Trie preloaded with: apple, app, apt, bat, ball