Skip to problem
←

Word Search II

Hard 0 attempts

You're given an m x n character board and a list of candidate strings words. Return every word from the list that can be traced out on the board by moving one letter at a time to a horizontally or vertically neighboring cell, without reusing any single cell more than once within that word's path.

Return each matching word only once, even when several paths spell it. Result order does not matter. Different words may reuse the same board cells; the no-reuse rule applies separately to each individual path. Diagonal moves are not allowed, and a word may be a prefix of another matching word.

Function contract

Implement findWords(board, words).

Output: Return each matching dictionary word exactly once, in any order. Return [] when none match.

Example 1

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

Input
board = [["a","a"]]
words = ["a","aa","aaa"]
Output
["a","aa"]
Visual Aid
Follow neighboring cells
abdc

abcd follows right → down → left. Each cell is used once; diagonal steps are not allowed.

Constraints
  • 1 <= m, n <= 12
  • 1 <= words.length <= 3 * 10^4
  • 1 <= words[i].length <= 10
  • board is rectangular and each cell contains one letter.
  • board and words contain only lowercase English letters.
  • All strings in words are unique.

Build a Trie from the word list, then DFS from every cell on the board. Traverse the Trie simultaneously — when a Trie node marks a complete word, add it to results. Delete a found word marker to avoid duplicate results, but continue exploring its longer-word descendants. After backtracking, remove an exhausted trie branch only when it has neither a word marker nor children. Always restore the board cell before returning.

javascript
function findWords(board, words) {
  const root = {};
  for (const word of words) {
    let node = root;
    for (const ch of word) {
      if (!node[ch]) node[ch] = {};
      node = node[ch];
    }
    node.word = word;
  }

  const rows = board.length, cols = board[0].length;
  const result = [];

  function dfs(r, c, node) {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return;
    const ch = board[r][c];
    if (ch === '#' || !node[ch]) return;

    const parent = node;
    node = node[ch];
    if (node.word) {
      result.push(node.word);
      delete node.word;
    }

    board[r][c] = '#';
    dfs(r + 1, c, node);
    dfs(r - 1, c, node);
    dfs(r, c + 1, node);
    dfs(r, c - 1, node);
    board[r][c] = ch;
    if (Object.keys(node).length === 0) delete parent[ch];
  }

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      dfs(r, c, root);
    }
  }
  return result;
}

Time: O(D + m·n·4·3^(L-1)), where D is the total dictionary characters and L is the maximum word length. Prefix and exhausted-branch pruning reduce the actual search. Space: O(D + L), excluding the returned words, for the trie and recursion stack.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript