Word Search II
Word Search II is LeetCode 212 (Hard). Given an m × n grid of letters and a list of words, return every word that can be spelled by a path through the grid.
- A path moves up, down, left or right to a neighbouring cell.
- A cell can be used at most once within one word.
- Each word goes into the answer once, in any order.
The grid is at most 12 × 12, but there can be 30,000 words of up to 10 letters, so running a separate grid search for each word is far too slow.
- m == board.length
- n == board[i].length
- 1 <= m, n <= 12
- board[i][j] is a lowercase English letter.
- 1 <= words.length <= 3 * 10⁴
- 1 <= words[i].length <= 10
- words[i] consists of lowercase English letters.
- All the strings of words are unique.
Intuition
Searching the grid once per word repeats the same walks: every word that starts with ea walks the same e → a cells again. Instead, put all the words in a trie and run one search that walks the grid and the trie together.
- Shared prefixes: a path in the grid sits on one trie node, and that node stands for every word starting with those letters, so each prefix is walked once.
- Instant pruning: if the next cell's letter is not a child of the current node, no word continues that way, so the search turns back at once.
- Reporting: a node that ends a word hands over the word the moment the path reaches it.
Many words searched in the same grid or text, where words share beginnings, points to a trie: one walk covers every word with the current prefix and stops when none fits.
Approach
Before reading on, decide what the search should know at each cell so it can give up as soon as no word in the list can continue. Then decide how to stop the same word being reported from two different paths.
Build a trie of all the words
Insert each word letter by letter and store the whole word at its last node. When a path reaches that node, the word is right there, with no need to rebuild it from the cells.
Start a search from every cell
Call dfs(r, c, root) for each cell. Inside, look up the cell's letter among the current node's children; if it is missing, return at once, since no word in the list continues with that letter here.
Report a word when its node is reached
Move to the child node. If it holds a word, add the word to the answer and take it off the node. The word is now done, and the node stays in the trie only while longer words still pass through it.
Mark the cell while it is on the path
Overwrite the cell with # before trying its four neighbours, and write the letter back afterwards. The mark stops this path from using the cell twice; writing it back makes the cell free again for every other path.
Remove branches with nothing left
After the neighbours are done, if the node has no children and no word, delete it from its parent. Once every word under a branch is found, later searches stop at its first letter instead of walking it again, which keeps large inputs inside the time limit.
Code in Python, C++ and Java
Common pitfalls
Stopping at the first word on a path
if word:
found.append(word)
returnif word:
found.append(word)
# keep going to the neighboursFor words = ["eat", "eats"] on [["e","a"],["s","t"]], the path e → a → t finds eat and returns, so the step on to s never happens and eats is missing.
Leaving the word on its node
if "$" in node:
found.append(node["$"])word = node.pop("$", None)
if word:
found.append(word)For board = [["a","b"],["b","a"]] and words = ["ab"], the grid spells ab along four different paths, so the answer lists it four times. Each word must appear once.
Not writing the letter back
board[r][c] = "#"
for ...:
dfs(nr, nc, node)board[r][c] = "#"
for ...:
dfs(nr, nc, node)
board[r][c] = chFor board = [["a","b"]] and words = ["ab", "ba"], the search from a finds ab and leaves both cells as #. The search from b then sees no letters at all, so ba is never found.
Edge cases
words = ["xyz"]Every cell fails the first lookup at the root, so the whole search is m × n dictionary lookups and returns [].
Complexity
Word Search II FAQ
Why is a trie needed here when Word Search does not need one?
Word Search (LeetCode 79) looks for one word, so plain backtracking is enough. Here up to 30,000 words would each need their own full search. The trie lets one search serve every word that shares the current prefix, and lets it stop the moment no word fits.
Is Word Search II the same as Word Boggle?
Almost. In Word Boggle a path may also step diagonally, so each cell has up to 8 neighbours instead of 4. The trie and backtracking stay the same; only the list of directions grows.
Why not keep the words in a hash set and test every path?
A set answers only "is this exact string a word?", not "does any word start like this?". Without that second answer the search cannot tell when to give up, so it walks every path of up to 10 cells from every cell, millions of paths on a 12 × 12 grid.