NeetCode 150, stage 8: Tries

← Trees · All 150 problems · Heap and Priority Queue →

A trie stores strings letter by letter, so words with the same prefix share nodes. This stage trains prefix questions. A lookup costs O(L) for a word of L letters, and the number of stored words does not change that cost. The last problem joins a trie with grid backtracking.

Problems on this page

Templates to memorize

Template A: Trie node, insert and walk

Signal

The problem says prefix, “starts with”, autocomplete or dictionary of words. You must answer many lookups on the same set of strings.

// TEMPLATE A: the trie node, INSERT and WALK.
type trieNode struct {
    // one slot for each lower-case letter; nil means "no child"
    children [26]*trieNode
    end      bool // true when a word ends at this node
}
 
func (root *trieNode) insert(word string) {
    node := root
    for i := 0; i < len(word); i++ {
        c := word[i] - 'a'
        if node.children[c] == nil {
            // 1. CREATE the child on first use
            node.children[c] = &trieNode{}
        }
        node = node.children[c] // 2. STEP down one letter
    }
    node.end = true // 3. MARK the end of the word
}
 
// walk returns the node at the end of s, or nil when the path stops.
// Search a word: the node is not nil AND node.end is true. Search a prefix:
// the node is not nil.
func (root *trieNode) walk(s string) *trieNode {
    node := root
    for i := 0; i < len(s); i++ {
        node = node.children[s[i]-'a'] // STEP down
        if node == nil {
            return nil
        }
    }
    return node
}

The moves are CREATE, STEP, then MARK for an insert, and STEP for a lookup. A word search and a prefix search use the same walk. Only the last test is different: a word search also needs node.end. If you forget that test, a search finds “app” after you insert only “apple”.

Say it

“Each node is one letter, and a flag marks the end of a word. Insert and search are O(L) for a word of length L, and the number of words does not matter.”

Template B: DFS on the trie for wildcards

Signal

The search pattern has a wildcard such as . that can be each letter. A hash set cannot answer that, because you cannot hash an unknown letter.

// TEMPLATE B: DFS on the trie. A '.' in the pattern can be each letter.
func matchFrom(node *trieNode, pattern string, i int) bool {
    if node == nil {
        return false // 1. STOP: the path ended before the pattern
    }
    if i == len(pattern) {
        return node.end // 2. END: a word must end exactly here
    }
    if pattern[i] != '.' {
        // 3. a letter: ONE path
        return matchFrom(node.children[pattern[i]-'a'], pattern, i+1)
    }
    for _, child := range node.children { // 4. a dot: BRANCH to each child
        if matchFrom(child, pattern, i+1) {
            return true
        }
    }
    return false
}

The moves are STOP on nil, test the END, follow ONE path for a letter, and BRANCH for a dot. Put the nil test first. Then the loop can pass each child with no test of its own.

Say it

“A letter follows one child. A dot tries all 26 children with a DFS. With no dots the search stays O(L).”

Template C: Trie plus grid backtracking

Signal

You must find many words in one grid of letters. A separate grid search for each word repeats the same walks.

// TEMPLATE C: the trie holds all the words, and one DFS walks the grid and
// the trie together.
type wordNode struct {
    children [26]*wordNode
    word     string // the full word when a word ends here, "" when not
}
 
func wordsInGrid(grid [][]byte, root *wordNode) []string {
    found := []string{}
    var dfs func(r, c int, parent *wordNode)
    dfs = func(r, c int, parent *wordNode) {
        if r < 0 || r >= len(grid) || c < 0 || c >= len(grid[0]) || grid[r][c] == '#' {
            return // out of the grid, or the cell is already in this path
        }
        letter := grid[r][c]
        node := parent.children[letter-'a']
        if node == nil {
            return // 1. PRUNE: no word continues with this letter
        }
        if node.word != "" {
            found = append(found, node.word) // 2. COLLECT
            node.word = ""                   // one time for each word
        }
        grid[r][c] = '#'  // 3. MARK
        dfs(r+1, c, node) // 4. EXPLORE the four neighbors
        dfs(r-1, c, node)
        dfs(r, c+1, node)
        dfs(r, c-1, node)
        grid[r][c] = letter // 5. UNMARK
    }
    for r := 0; r < len(grid); r++ {
        for c := 0; c < len(grid[0]); c++ {
            dfs(r, c, root) // each cell can be the first letter
        }
    }
    return found
}

The moves are PRUNE, COLLECT, MARK, EXPLORE, then UNMARK. The DFS moves in the grid and in the trie at the same time. The trie stops a path when no word continues with that letter. Clear node.word after you collect it, or the result gets the same word again from another path. The mark and unmark moves are the grid template of the Backtracking stage.

Say it

“I put all the words in a trie and run one backtracking DFS from each cell. The trie prunes each path that is not a prefix of some word.”

Mistakes in this stage

  • word[i] is a byte, not a letter index. Subtract 'a' before you use it as an index.
  • A [26]*trieNode array works only for lower-case letters. For other characters, use a map[rune]*trieNode.
  • A method on a nil node pointer panics when it reads a field. Test for nil before you read node.end.
  • The mark '#' is not a lower-case letter. Test for it before you compute letter-'a'.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

208. Implement Trie (Prefix Tree)

LeetCode 208 · Medium

211. Design Add and Search Words Data Structure

LeetCode 211 · Medium

212. Word Search II

LeetCode 212 · Hard


← Trees · All 150 problems · Heap and Priority Queue →