Skip to content

Word Search II

Find all listed words that can be traced on a letter grid, searching for every word at once with a trie.

HardTries
Solve on LeetCode

The problem

You get an m x n board of letters and a list of distinct words. A word is on the board if you can spell it by moving between cells that share a side, without using any cell twice in the same word. Return every word from the list that is on the board, in any order.

Input board = [["c", "a", "t"], ["r", "o", "p"], ["e", "a", "d"]], words = ["cat", "road", "rope", "pod", "care"]

Output ["cat", "road"]

cat runs along the top row and road goes r, o, a, d. In rope, the p has no e next to it.

Input board = [["a", "b"], ["c", "d"]], words = ["abdc", "abc", "acdb"]

Output ["abdc", "acdb"]

Both found words go round the square; abc would need a diagonal step from b to c.

Key constraint: There can be 30,000 words on a board of up to 12 x 12, so a separate search for each word repeats a lot of work.

How to spot the pattern

  • Many words to find in the same grid, and they share prefixes.
  • A grid DFS that should stop as soon as the letters so far start no word.

The idea

Searching for each word separately repeats the same grid walks for words that share a prefix. Instead, put all the words in a trie and run one DFS from each cell, moving down the trie as you step onto letters; when the trie has no child for a letter, no word continues that way, so the branch stops at once. When you reach a node that ends a word, record the word and clear it so it is reported once, and remove trie nodes with nothing left below them so later searches skip them.

Brute force: Run a separate Word Search DFS for each word, which repeats the grid walk for every word and takes O(W * m * n * 3^L) time.

Step by step

  1. 1Insert every word into a trie, storing the full word on its last node.
  2. 2Start a DFS from every cell with the trie root.
  3. 3In the DFS, stop if the cell is off the board, already used on this path, or its letter is not a child of the current node; otherwise move to that child.
  4. 4If the child holds a word, add it to the answer and clear it.
  5. 5Mark the cell as used, recurse into its 4 neighbors, then restore the cell.
  6. 6If the child now has no children and no word, delete it from its parent.

Code

class TrieNode:
    def __init__(self):
        self.children = {}  # letter -> TrieNode
        self.word = None  # the full word that ends at this node, if any


class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        root = TrieNode()
        for w in words:
            node = root
            for ch in w:
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.word = w

        rows, cols = len(board), len(board[0])
        found = []

        def dfs(r: int, c: int, parent: TrieNode) -> None:
            if r < 0 or r >= rows or c < 0 or c >= cols:
                return
            ch = board[r][c]
            node = parent.children.get(ch)  # None for a used cell or a dead-end letter
            if node is None:
                return
            if node.word is not None:
                found.append(node.word)
                node.word = None  # report each word only once
            board[r][c] = "#"  # mark the cell as used on this path
            dfs(r + 1, c, node)
            dfs(r - 1, c, node)
            dfs(r, c + 1, node)
            dfs(r, c - 1, node)
            board[r][c] = ch  # free the cell again when backtracking
            if not node.children and node.word is None:
                del parent.children[ch]  # prune: nothing is left to find below this node

        for r in range(rows):
            for c in range(cols):
                dfs(r, c, root)
        return found

Complexity

Time

O(m * n * 4 * 3^(L - 1))

Space

O(total letters)

L is the longest word, at most 10 letters: each start cell explores paths of at most L cells, with 4 directions first and at most 3 after that. The trie holds every letter of every word, and pruning makes the real work much smaller.

Watch out for

  • Reporting a word twice when two different paths spell it; clear the word once it is found.
  • Forgetting to restore the cell after the recursion, which hides that letter from every later path.
  • Searching for each word on its own, which is too slow when there are thousands of words.

Follow-up questions

Why prune trie nodes?

Once every word below a node has been found, that branch can't add anything. Removing it stops later DFS calls from walking those letters again, which matters on boards full of repeated letters.

How is this different from Word Search?

Word Search checks a single word, so a plain DFS that compares letters by index is enough. With many words, the trie lets one DFS check all of them together.

In Hinglish

Har word ke liye alag search mat chalao. Saare words trie mein daalo aur board par ek hi DFS chalao; trie mein agla letter na mile toh wahin ruk jao.

Related problems