Word Search II (LeetCode 212): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Build a trie from
words. Walk each word character by character, creating child nodes as needed, and setp.word = won the final node. - Loop over every cell
(i, j)of the board and start a DFS from it with the trie root. - In the DFS, read
c = board[i][j]. Ifcis#(already on the path) or not a child of the current trie node, return. - Move the trie pointer to
p.children[c]. If that node has aword, append it toresand setp.word = Noneto prevent duplicates. - Mark the cell by setting
board[i][j] = '#', then recurse into the up, left, down and right neighbors that are inside the grid. - After exploring the neighbors, restore
board[i][j] = cso other paths can use the cell. - Return
resafter every starting cell has been tried.
Step-by-step example
board = [["o","a"],["h","t"]], words = ["oat","oh","hat"]
- The trie root has children
o(leading to "oat" and "oh") andh(leading to "hat"). - 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), letterh, which is a child of theonode. That node holds "oh", so append it and clear the word. - From (1,0), the only unvisited neighbor is (1,1) with
t, which is not a child of "oh", so backtrack and restoreh. - Back at (0,0), go right to (0,1), letter
a, a child ofo. From there, down to (1,1), lettert, completes "oat", so append it. - Starting cells (0,1) and (1,1) are not root children. Starting at (1,0) with
hfinds no neighbora, so "hat" is never found. - 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 root1public class Solution {
2 static class TrieNode {
3 TrieNode[] children = new TrieNode[26];
4 String word = null;
5 }
6
7 public List<String> findWords(char[][] board, String[] words) {
8 List<String> res = new ArrayList<>();
9 TrieNode root = buildTrie(words);
10 for (int i = 0; i < board.length; i++) {
11 for (int j = 0; j < board[0].length; j++) {
12 dfs(board, i, j, root, res);
13 }
14 }
15 return res;
16 }
17
18 public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
19 char c = board[i][j];
20 if (c == '#' || p.children[c - 'a'] == null) return;
21 p = p.children[c - 'a'];
22 if (p.word != null) { // found one
23 res.add(p.word);
24 p.word = null; // de-duplicate
25 }
26
27 board[i][j] = '#';
28 if (i > 0) dfs(board, i - 1, j, p, res);
29 if (j > 0) dfs(board, i, j - 1, p, res);
30 if (i < board.length - 1) dfs(board, i + 1, j, p, res);
31 if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
32 board[i][j] = c;
33 }
34
35 public TrieNode buildTrie(String[] words) {
36 TrieNode root = new TrieNode();
37 for (String w : words) {
38 TrieNode p = root;
39 for (char c : w.toCharArray()) {
40 int i = c - 'a';
41 if (p.children[i] == null) p.children[i] = new TrieNode();
42 p = p.children[i];
43 }
44 p.word = w;
45 }
46 return root;
47 }
48}1class TrieNode {
2public:
3 unordered_map<char, TrieNode*> children;
4 string* word = nullptr;
5 ~TrieNode() {
6 for (auto& pair : children) delete pair.second;
7 }
8};
9
10class Solution {
11public:
12 vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
13 TrieNode* root = buildTrie(words);
14 vector<string> res;
15 for (int i = 0; i < board.size(); ++i) {
16 for (int j = 0; j < board[0].size(); ++j) {
17 dfs(board, i, j, root, res);
18 }
19 }
20 delete root; // basic cleanup
21 return res;
22 }
23
24 void dfs(vector<vector<char>>& board, int i, int j, TrieNode* p, vector<string>& res) {
25 char c = board[i][j];
26 if (c == '#' || !p->children.count(c)) return;
27 p = p->children[c];
28 if (p->word) {
29 res.push_back(*p->word);
30 p->word = nullptr; // dedupe
31 }
32
33 board[i][j] = '#';
34 if (i > 0) dfs(board, i - 1, j, p, res);
35 if (j > 0) dfs(board, i, j - 1, p, res);
36 if (i < board.size() - 1) dfs(board, i + 1, j, p, res);
37 if (j < board[0].size() - 1) dfs(board, i, j + 1, p, res);
38 board[i][j] = c;
39 }
40
41 TrieNode* buildTrie(vector<string>& words) {
42 TrieNode* root = new TrieNode();
43 for (string& w : words) {
44 TrieNode* p = root;
45 for (char c : w) {
46 if (!p->children.count(c)) p->children[c] = new TrieNode();
47 p = p->children[c];
48 }
49 p->word = &w; // pointer to word in original vector
50 }
51 return root;
52 }
53};Time and space complexity
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.
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.wordafter 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.