Coding Interview PatternsWord Search II
HardBacktracking
Word Search II
Explanation & Solution
Description
Given an m x n board of characters and a list of strings words, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Input:board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
0
oath
1
pea
2
eat
3
rain
Output:["eat","oath"]
0
eat
1
oath
Explanation: The words "eat" and "oath" can be formed by traversing adjacent cells on the board. "pea" and "rain" cannot be formed.
Constraints
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j]is a lowercase English letter1 <= words.length <= 3 * 10⁴1 <= words[i].length <= 10words[i]consists of lowercase English letters- All strings in
wordsare unique
Approach
Backtracking pattern
1. Build a Trie from the Word List
- Create a trie root node with a
childrenmap - For each word in the list, insert it character by character into the trie
- Store the complete word at the terminal node (
node.word = word) for easy retrieval
2. DFS from Every Cell
- Iterate through every cell
(r, c)on the board - Start a DFS traversal using the trie root as the starting node
- The trie guides the search — only explore paths that match trie branches
3. DFS Traversal Logic
- Check bounds and whether the cell has been visited (marked
'#') - Check if the current character exists in the trie node's children
- If the next trie node has a
wordproperty, add it to results and set it tonullto avoid duplicates
4. Backtracking
- Mark the current cell as visited by replacing its character with
'#' - Recursively explore all four directions (up, down, left, right)
- Restore the cell's original character after exploring all directions
5. Return Sorted Results
- After all DFS traversals complete, sort the result array alphabetically
- Return the list of found words
Key Insight
- Using a trie to store all target words lets us search for multiple words simultaneously during a single board traversal, avoiding repeated DFS for each word
- Setting
node.word = nullafter finding a word prevents duplicate entries without needing a separate set
Time
O(m * n * 4^L) where L is the max word length — but the trie prunes invalid paths earlySpace
O(W * L) for the trie, where W is the number of words and L is the average lengthVisualization
Input:
DFS Traversal4×4 grid
output—
Press play to start dfs traversal
CurrentQueuedVisitedSource
99 steps