05. Word Search II (Board Search with Trie)

Difficulty:HardPattern:Trie + Grid DFS BacktrackingTime:O(M * N * 4^L)Space:O(W * L)

Given an $m \times n$ board of characters and a list of strings words, return all words on the board.

How It Works & Algorithmic Design

Solves using Prefix Trie Tree + Grid Backtracking DFS:

  1. Build Prefix Trie: Insert all words into Trie. Store complete word reference at terminal leaf nodes.
  2. Grid Traversal DFS dfs(r, c, trieNode):
    • Base Case: if cell out of bounds or board[r][c] === '#' or character not in trieNode.children, return.
    • Matching Child: step into childNode.
    • Word Discovered: if childNode.word !== null, push to result and set childNode.word = null (prevents duplicates).
    • Mark visited board[r][c] = '#' and recurse 4 directions.
    • Restore cell board[r][c] = originalChar.

Why This Approach Works Best

Trie prefix matching prunes search paths across thousands of words simultaneously in $O(M \cdot N \cdot 4^L)$ worst-case.

Example Walkthrough

Input Grid

[["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]

Grid and word dictionary.

Words Found

"oath", "eat"

Valid board word paths.

Output

["oath", "eat"]

Discovered words.

Answer: Word Search II Trie implementation

function findWords(board, words) {
  const root = {};
  for (const w of words) {
    let node = root;
    for (const c of w) {
      if (!node[c]) node[c] = {};
      node = node[c];
    }
    node.word = w;
  }
  const res = [];
  const m = board.length, n = board[0].length;
  function dfs(r, c, node) {
    const ch = board[r][c];
    if (!node[ch]) return;
    node = node[ch];
    if (node.word) {
      res.push(node.word);
      node.word = null;
    }
    board[r][c] = '#';
    const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
    for (const [dr, dc] of dirs) {
      const nr = r + dr, nc = c + dc;
      if (nr >= 0 && nc >= 0 && nr < m && nc < n && board[nr][nc] !== '#') {
        dfs(nr, nc, node);
      }
    }
    board[r][c] = ch;
  }
  for (let r = 0; r < m; r++) {
    for (let c = 0; c < n; c++) {
      dfs(r, c, root);
    }
  }
  return res;
}

Build Prefix Trie and perform 4-directional grid DFS backtracking to find matching words.

Key Takeaways
  • Store complete word string directly inside Trie leaf node.

  • Set node.word = null when found to avoid duplicate results.

  • Trie prefix checks prune invalid board branches fast.