Skip to main content
38

Word Search II

Hardtriebacktracking

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TriesRead the beginner guide

You're given an m x n grid of letters board and a list of words. Return every word from the list that can be traced on the board, in any order.

Understand the problem

  • To trace a word, start on a cell holding its first letter, then step to a neighboring cell for each next letter.
  • Neighbors are cells directly up, down, left or right (not diagonal).
  • The same cell can't be used twice within one word.
  • Each found word is reported once, even if it can be traced in several ways.

This is Word Search (one word on a board), but with many words at once. If you haven't solved Word Search yet, start there.

Example 1

text
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"]
  • oath: o (row 0, col 0) → a (right) → t (down) → h (down).
  • eat: e (row 1, col 3) → a (left) → t (left).
  • pea: there's no p on the board.
  • rain: r, a, i, n exist, but not as a connected path.

Example 2

text
board = [["a","b"],
         ["c","d"]]
words = ["abcb"]

Output: []

a → b → c already fails: c isn't next to b. And abcb would need b twice.

Constraints

  • 1 <= m, n <= 12
  • 1 <= words.length <= 3 * 10^4
  • 1 <= words[i].length <= 10
  • All letters are lowercase English letters, and the words are unique.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Put all the words in a trie, then run one DFS from every cell that moves through the board and the trie at the same time, stopping as soon as no word starts with the letters traced so far.

    The naive approach (and why it's slow)

    Run Word Search separately for each word: for each of up to 30,000 words, try a DFS from every cell. Lots of the work repeats: words that share a beginning, like oat, oath and oaths, re-walk exactly the same cells again and again.

    The key insight

    Search for all words at once with a trie:

    1. Insert every word into a trie. On the node where a word ends, store the word itself (so we can report it directly).
    2. From every cell, start a DFS. Each time you step onto a cell with letter c, also step down to the trie child c.
    3. If the trie has no child for c, then no word starts with the letters you've traced: stop right away. This is where all the speed comes from.
    4. If the trie node holds a word, add it to the answer and clear it, so it's reported only once.
    5. While you're on a cell, mark it as used (replace its letter with #). When you step back, put the letter back. Undoing your change like this is called backtracking.

    Step by step

    Words oath, pea, eat, rain. Trace from the top-left o:

    Board cellLetterTrie path so farWhat happens
    (0, 0)ootrie has o (from oath): continue
    (0, 1), rightao atrie has it: continue
    (1, 1), downto a ttrie has it: continue
    (2, 1), downho a t ha word ends here: record oath

    Starting from (1, 0), the letter e is in the trie (from eat), but its neighbors are o, t and i, and none of them follow e in the trie, so we stop after one step. From (0, 1), the a isn't the first letter of any word: stopped before even moving.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With m × n cells and L = the longest word:

    • Time: in the worst case about O(m · n · 4 · 3^(L-1)): from each cell, the first step has 4 directions and each later one at most 3 (you can't go back). The trie pruning makes the real cost far lower.
    • Memory: O(total letters in all words) for the trie, plus O(L) for the recursion.

    Common mistakes

    • Reporting a word twice when it can be traced in two ways. Clear the word from the trie node once found.
    • Forgetting to restore the cell after exploring. Other paths need that letter.
    • Reusing a cell in one word. That's what the # mark prevents.

    Going deeper

    An extra pruning: after exploring a trie node, if it has no children left and no word, delete it from its parent. Words already found then stop pulling the search into dead branches. The reference solution does this, and it matters on boards full of repeated letters, like a grid of all as.

    Reference solution

    js
    /**
     * @param {string[][]} board
     * @param {string[]} words
     * @return {string[]}
     */
    export default function findWords(board, words) {
      // 1. Put every word in a trie. `word` holds the full word when one ends at a node.
      const root = { children: new Map(), word: null }
      for (const word of words) {
        let node = root
        for (const char of word) {
          if (!node.children.has(char)) node.children.set(char, { children: new Map(), word: null })
          node = node.children.get(char)
        }
        node.word = word
      }
    
      const rows = board.length
      const cols = board[0].length
      const found = []
    
      // 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
      function dfs(r, c, parent) {
        const char = board[r][c]
        const node = parent.children.get(char)
        // No word continues with this letter: stop exploring this path.
        if (!node) return
        if (node.word !== null) {
          found.push(node.word)
          node.word = null // report each word only once
        }
        board[r][c] = '#' // mark the cell as used for this path
        for (const [dr, dc] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1],
        ]) {
          const nr = r + dr
          const nc = c + dc
          // Stay on the board, and don't reuse a cell on the current path.
          if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') {
            dfs(nr, nc, node)
          }
        }
        board[r][c] = char // backtrack: give the letter back for other paths
        // Extra pruning: a trie branch with nothing left to find can be removed.
        if (node.children.size === 0 && node.word === null) parent.children.delete(char)
      }
    
      // 3. Try starting from every cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) dfs(r, c, root)
      }
      return found
    }
    ts
    // A trie node. `word` holds the full word when one ends at this node.
    type TrieNode = { children: Map<string, TrieNode>; word: string | null }
    
    export default function findWords(board: string[][], words: string[]): string[] {
      // 1. Put every word in a trie.
      const root: TrieNode = { children: new Map(), word: null }
      for (const word of words) {
        let node = root
        for (const char of word) {
          let child = node.children.get(char)
          if (!child) {
            child = { children: new Map(), word: null }
            node.children.set(char, child)
          }
          node = child
        }
        node.word = word
      }
    
      const rows = board.length
      const cols = board[0].length
      const found: string[] = []
    
      // 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
      function dfs(r: number, c: number, parent: TrieNode): void {
        const char = board[r][c]
        const node = parent.children.get(char)
        // No word continues with this letter: stop exploring this path.
        if (!node) return
        if (node.word !== null) {
          found.push(node.word)
          node.word = null // report each word only once
        }
        board[r][c] = '#' // mark the cell as used for this path
        for (const [dr, dc] of [
          [1, 0],
          [-1, 0],
          [0, 1],
          [0, -1],
        ]) {
          const nr = r + dr
          const nc = c + dc
          // Stay on the board, and don't reuse a cell on the current path.
          if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') {
            dfs(nr, nc, node)
          }
        }
        board[r][c] = char // backtrack: give the letter back for other paths
        // Extra pruning: a trie branch with nothing left to find can be removed.
        if (node.children.size === 0 && node.word === null) parent.children.delete(char)
      }
    
      // 3. Try starting from every cell.
      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) dfs(r, c, root)
      }
      return found
    }
    python
    def find_words(board: list[list[str]], words: list[str]) -> list[str]:
        # 1. Put every word in a trie made of nested dicts. The key "$" holds the full word
        #    when one ends at that node.
        root = {}
        for word in words:
            node = root
            for char in word:
                node = node.setdefault(char, {})
            node["$"] = word
    
        rows, cols = len(board), len(board[0])
        found = []
    
        # 2. Step onto cell (r, c) and, at the same time, down the trie from `parent`.
        def dfs(r: int, c: int, parent: dict) -> None:
            char = board[r][c]
            node = parent.get(char)
            # No word continues with this letter: stop exploring this path.
            if node is None:
                return
            # pop() removes the word, so each word is reported only once.
            word = node.pop("$", None)
            if word is not None:
                found.append(word)
            board[r][c] = "#"  # mark the cell as used for this path
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                # Stay on the board, and don't reuse a cell on the current path.
                if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
                    dfs(nr, nc, node)
            board[r][c] = char  # backtrack: give the letter back for other paths
            # Extra pruning: a trie branch with nothing left to find can be removed.
            if not node:
                del parent[char]
    
        # 3. Try starting from every cell.
        for r in range(rows):
            for c in range(cols):
                dfs(r, c, root)
        return found