Word Search II (LeetCode 212): Solution and Explanation

Hard
Array
String
Backtracking
Trie
Matrix

You get a grid of letters and a list of words. Return every word from the list that can be spelled by a path of horizontally or vertically adjacent cells, where no cell is used twice in the same word.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious starting point is the single-word version: for each word, try every cell as a starting point and run a backtracking DFS that follows matching letters. That works, but with thousands of words it repeats the same exploration again and again. Searching for "oath" and "oat" walks exactly the same cells for the first three letters, and every word that starts with a letter that never appears in a useful position still triggers a full scan of the board.

The fix is to flip the loops around. Instead of asking "where is this word?" for each word, walk the board once and ask "which words could the current path still become?" A trie answers that question in constant time per step. Each trie node represents a prefix, and its children are the letters that can extend it into some word in the list. During the DFS you carry a pointer into the trie alongside your position in the grid. If the next cell's letter is not a child of the current trie node, no word in the list continues along this path, so you prune immediately.

Two small tricks make the implementation clean. First, store the full word on the trie node where it ends, so when the DFS reaches that node you can append it to the result directly without rebuilding the string from the path. Then clear that field so the same word is not reported twice when it can be spelled along more than one path. Second, mark visited cells by temporarily overwriting the board letter with # and restoring it on the way back. That avoids a separate visited set and lets the same check (c == '#') reject reused cells.

Approach: Trie plus backtracking DFS

  1. Build a trie from words. Walk each word character by character, creating child nodes as needed, and set p.word = w on the final node.
  2. Loop over every cell (i, j) of the board and start a DFS from it with the trie root.
  3. In the DFS, read c = board[i][j]. If c is # (already on the path) or not a child of the current trie node, return.
  4. Move the trie pointer to p.children[c]. If that node has a word, append it to res and set p.word = None to prevent duplicates.
  5. Mark the cell by setting board[i][j] = '#', then recurse into the up, left, down and right neighbors that are inside the grid.
  6. After exploring the neighbors, restore board[i][j] = c so other paths can use the cell.
  7. Return res after every starting cell has been tried.

Step-by-step example

board = [["o","a"],["h","t"]], words = ["oat","oh","hat"]
  1. The trie root has children o (leading to "oat" and "oh") and h (leading to "hat").
  2. Start at (0,0) with letter o, which is a root child. Mark it #. Up and left are out of bounds, so go down to (1,0), letter h, which is a child of the o node. That node holds "oh", so append it and clear the word.
  3. From (1,0), the only unvisited neighbor is (1,1) with t, which is not a child of "oh", so backtrack and restore h.
  4. Back at (0,0), go right to (0,1), letter a, a child of o. From there, down to (1,1), letter t, completes "oat", so append it.
  5. Starting cells (0,1) and (1,1) are not root children. Starting at (1,0) with h finds no neighbor a, so "hat" is never found.
  6. The result is ["oh", "oat"].

Code: Python, Java, C++

1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.word = None
5
6class Solution:
7    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
8        root = self.buildTrie(words)
9        res = []
10        for i in range(len(board)):
11            for j in range(len(board[0])):
12                self.dfs(board, i, j, root, res)
13        return res
14
15    def dfs(self, board, i, j, p, res):
16        c = board[i][j]
17        if c == '#' or c not in p.children: return
18        p = p.children[c]
19        if p.word:
20            res.append(p.word)
21            p.word = None
22
23        board[i][j] = '#'
24        if i > 0: self.dfs(board, i-1, j, p, res)
25        if j > 0: self.dfs(board, i, j-1, p, res)
26        if i < len(board)-1: self.dfs(board, i+1, j, p, res)
27        if j < len(board[0])-1: self.dfs(board, i, j+1, p, res)
28        board[i][j] = c
29
30    def buildTrie(self, words):
31        root = TrieNode()
32        for w in words:
33            p = root
34            for c in w:
35                if c not in p.children: p.children[c] = TrieNode()
36                p = p.children[c]
37            p.word = w
38        return root

Time and space complexity

Time

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

Building the trie costs O(total letters in words). Each of the m × n starting cells can launch a DFS that branches four ways on the first step and at most three ways afterward (it never goes back to the cell it came from), to a depth of at most L, the longest word length. Trie pruning makes the real cost far smaller in practice.

Space

O(W)

The trie stores at most one node per letter across all words, so it uses O(W) where W is the total number of characters. The recursion stack adds O(L), and marking cells in place avoids a visited set.

Other approaches

Run Word Search once per word (time O(k × m × n × 3^L), space O(L))

Apply the single-word backtracking search to each word separately. It is simpler to write but repeats shared prefixes and scans the board once per word, which times out when the word list is large.

Trie with leaf pruning (time O(m × n × 4 × 3^(L - 1)), space O(W))

Same algorithm, but after a word is found, delete trie nodes that no longer lead to any unfound word. Later searches then stop earlier, which is a meaningful speedup on boards where many words share prefixes.

Common mistakes

  • Forgetting to clear p.word after recording it. A word that can be spelled along two different paths would then appear twice in the output.
  • Not restoring board[i][j] after the recursive calls. The cell stays marked as #, so later starting points cannot use it and valid words are missed.
  • Checking membership in the trie after marking the cell, or marking the cell before confirming it matches. The guard must run first so a mismatched cell is never altered.
  • Rebuilding the current word as a string at every step and looking it up in a set. That adds O(L) work per step and loses the prefix pruning that makes the trie worthwhile.

Frequently asked questions

Why use a trie for Word Search II?

A trie lets one DFS search for all words at once. Each step checks whether the current path is a prefix of any word in constant time, so dead-end paths are cut immediately instead of being explored once per word.

What is the time complexity of Word Search II?

Roughly O(m × n × 4 × 3^(L - 1)), where L is the longest word, plus O(W) to build the trie. The exponential term is a loose upper bound; trie pruning keeps actual runs much faster.

How do you avoid duplicate words in the result?

Store the word on its terminal trie node and set it to None the first time it is found. Any later path that reaches the same node sees no word and adds nothing.

Can I reuse a cell within the same word?

No. That is why the cell is overwritten with # while it is on the current path and restored when the DFS backtracks.