Tries · Pattern 2 of 3

Trie + backtracking: find many words at once

Put all the words in a trie, then backtrack over the grid while walking the trie at the same time. The moment the current path is not a prefix of any word, stop: that pruning is what makes it fast.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Find every word from a list on a board or in a string
  • Checking each word separately would repeat the same search many times
  • Paths that can be cut off as soon as no word continues them

The template

Trie + Backtracking
static class Node { Node[] next = new Node[26]; String word; }   // word is set on end nodes

List<String> findWords(char[][] board, String[] words) {
    Node root = new Node();
    for (String w : words) {
        Node cur = root;
        for (char c : w.toCharArray()) {
            if (cur.next[c - 'a'] == null) cur.next[c - 'a'] = new Node();
            cur = cur.next[c - 'a'];
        }
        cur.word = w;
    }
    List<String> res = new ArrayList<>();
    for (int r = 0; r < board.length; r++)
        for (int c = 0; c < board[0].length; c++) dfs(board, r, c, root, res);
    return res;
}

void dfs(char[][] b, int r, int c, Node parent, List<String> res) {
    if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] == '#') return;
    Node node = parent.next[b[r][c] - 'a'];
    if (node == null) return;                       // no word continues this way: prune
    if (node.word != null) { res.add(node.word); node.word = null; }   // found; never add it twice
    char ch = b[r][c];
    b[r][c] = '#';                                  // mark as used on this path
    dfs(b, r + 1, c, node, res); dfs(b, r - 1, c, node, res);
    dfs(b, r, c + 1, node, res); dfs(b, r, c - 1, node, res);
    b[r][c] = ch;                                   // undo
}

The variations

  1. 1Grid search with a trie

    Start a DFS from every cell, carrying the trie node for the path so far. Step only to a neighbour whose letter is a child of that node. Each found word is removed from its node, and pruning empty branches makes later searches even faster.

Mistakes to avoid

  • Running a separate word search for every word: the trie lets one DFS check all of them together.
  • Adding the same word twice when it can be traced along two paths: clear it from the node once found.
  • Forgetting to restore the cell after the DFS, so later paths think it is still used.
Next: Bitwise trie: the largest XOR, bit by bit →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.