Word Search II solution explained
To find every word from a list that can be traced on a letter grid, put all the words in a trie, then run one backtracking search from each cell that walks the grid and the trie together: a step is taken only if the next letter continues some word in the trie. Record a word when you reach its end node, remove it so it is reported once, and prune trie branches that have nothing left. This replaces one full grid search per word with a single shared search.
By Evin JohnPublished 8 min read
The problem, in plain terms
You get a board of letters and a list of candidate words. Return every candidate that can be formed by starting on some cell and moving up, down, left or right one cell per letter, without using the same cell twice in one word. Each word should appear once in the answer even if it can be traced in several places or appears twice in the list. Order usually does not matter.
s l a t
t o n e
r a i n
words: salt, stone, tone, train, rain, to, lane, tote
found: stone, tone, train, rain, to, lane
missed: salt (s and a are not adjacent), tote (needs the same t twice)Ask how many words and how long they can be, whether the list can contain duplicates, and whether the board may be modified temporarily. The number of words is what makes the trie worthwhile.
How the problem is used in interviews
This is a common hard question because it combines two patterns: backtracking on a grid and a prefix tree. Interviewers usually expect you to start from the single-word solution, explain why it scales badly with many words, and then introduce the trie. The pruning details (removing found words, deleting dead branches) separate a working answer from a fast one, and the duplicate handling is a frequent bug.
A slower starting idea
Run the single-word backtracking search for every word in the list and keep those that succeed. It is correct and easy to justify, but for W words it costs roughly W times the cost of one search, about O(W × R × C × 3^L). Words that share a beginning, like tone and to, are explored from scratch each time. With thousands of words this is far too slow.
The optimal approach: one search guided by a trie
Pattern: trie plus backtracking. Insert every word into a trie and store the whole word at its final node. Then start a depth-first search at each cell with the trie root as the current node. At each step, look up the cell's letter among the current node's children. If there is no such child, no word continues this way, so stop. If the child holds a word, add it to the results and clear it so it is not added again. Mark the cell as used, recurse into the four neighbors with the child as the current node, and restore the cell. Finally, if the child has no children and no word left, delete it from its parent, which makes later searches skip it entirely.
def find_words(board, words):
root = {} # nested dicts; key None holds a word
for w in words:
node = root
for ch in w:
node = node.setdefault(ch, {})
node[None] = w
rows, cols = len(board), len(board[0])
found = []
def dfs(r, c, parent):
ch = board[r][c]
node = parent.get(ch) # also fails on a used cell ("#")
if node is None:
return
word = node.pop(None, None) # take it once, so no duplicates
if word is not None:
found.append(word)
board[r][c] = "#"
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols:
dfs(nr, nc, node)
board[r][c] = ch
if not node: # nothing left below: prune branch
del parent[ch]
for r in range(rows):
for c in range(cols):
dfs(r, c, root)
return foundNotice that finding a word does not stop the search. In the example, to and tone share a path: reaching the o records to, and the search carries on through n and e to record tone. That is why the word is cleared rather than returned.
#include <array>
#include <functional>
#include <string>
#include <vector>
std::vector<std::string> findWords(std::vector<std::vector<char>>& board,
const std::vector<std::string>& words) {
// Trie stored in parallel vectors; node 0 is the root.
std::vector<std::array<int, 26>> next(1);
next[0].fill(-1);
std::vector<int> wordAt(1, -1), children(1, 0);
for (int w = 0; w < (int)words.size(); ++w) {
int cur = 0;
for (char ch : words[w]) {
int k = ch - 'a';
if (next[cur][k] == -1) {
next[cur][k] = (int)next.size();
next.emplace_back();
next.back().fill(-1);
wordAt.push_back(-1);
children.push_back(0);
++children[cur];
}
cur = next[cur][k];
}
wordAt[cur] = w;
}
const int rows = board.size(), cols = board[0].size();
std::vector<std::string> found;
std::function<void(int, int, int)> dfs = [&](int r, int c, int parent) {
char ch = board[r][c];
if (ch == '#') return; // used on this path
int node = next[parent][ch - 'a'];
if (node == -1) return;
if (wordAt[node] != -1) { // report once
found.push_back(words[wordAt[node]]);
wordAt[node] = -1;
}
board[r][c] = '#';
const int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
for (int d = 0; d < 4; ++d) {
int nr = r + dr[d], nc = c + dc[d];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols) dfs(nr, nc, node);
}
board[r][c] = ch;
if (children[node] == 0 && wordAt[node] == -1) { // dead branch
next[parent][ch - 'a'] = -1;
--children[parent];
}
};
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c) dfs(r, c, 0);
return found;
}The C++ version assumes lowercase letters a to z, as most versions of the problem do. Storing children in an array per node is fast; if the alphabet were larger or unknown, a hash map per node (as in the Python version) is the safer choice.
Complexity summary
| Approach | Time (worst case) | Extra space |
|---|---|---|
| Single-word search for each word | O(W × R × C × 3^L) | O(L) recursion |
| Trie-guided search | O(S) to build, plus O(R × C × 3^L) to search | O(S) trie plus O(L) recursion |
| Trie-guided search with pruning | Same bound, much faster once words are found | Trie shrinks as words are found |
The search bound no longer grows with the number of words, because every branch of the walk is shared by all words with that prefix. In practice the trie also cuts most branches after one or two letters.
Edge cases to try
- The same word listed twice, and a word findable in two places: each must appear once in the output.
- A word that is a prefix of another (to and tone): both must be found.
- A word longer than the number of cells.
- A word that needs a cell twice, like tote above.
- An empty word list, or a one-cell board.
Pitfalls
- Returning as soon as a word is found, which misses longer words on the same path.
- Adding a word every time it is reached, producing duplicates.
- Pruning a trie node before its neighbors have been explored, or pruning a node that still holds an unfound word.
- Keeping a separate visited set and a trie walk out of sync with each other.
- Building the trie but still looping over the words list during the search.
How to explain it out loud
Fictional example
- Candidate
- For one word I'd backtrack from every cell. For many words that repeats the same walks for shared prefixes, so I'll put all the words in a trie and walk the grid and the trie together.
- Candidate
- At each cell I move to the trie child for that letter. If there isn't one, no word continues, so I stop. If the child ends a word, I record it and clear it so it's reported once, then keep going because a longer word might continue.
- Candidate
- After exploring, if that trie node is now empty I delete it, so later starts skip it. The search cost no longer multiplies by the number of words.
Related problems
Solve Word Search first if the backtracking itself is new. The trie used here is built in a different style in Implement Trie. For a very different use of a small persistent structure, compare Kth Largest Element in a Stream.
How Natively can help you prepare
Hard problems with two moving parts are where a second set of eyes helps during practice. On Mac or Windows, Natively can read the board and word list from a screenshot, suggest the trie-plus-backtracking plan, and point at the duplicate and prefix cases. Afterward, the transcript of your mock round shows whether you explained why the trie beats per-word search. See the AI interview assistant.
Questions people ask
How do you solve Word Search II?
Insert all words into a trie, then backtrack from every cell while walking the trie: only step to a neighbor if its letter continues some word. Record a word when you reach its end node, clear it so it is reported once, and keep searching for longer words.
Why use a trie for Word Search II?
Searching for each word separately repeats the same grid walks for words that share prefixes. A trie lets one search follow all of them at once and stop as soon as no word continues.
What is the time complexity of Word Search II?
Building the trie is O(S) for S total letters. The search is O(R × C × 3^L) in the worst case for an R by C board and longest word L, without the extra factor for the number of words.
How do you avoid duplicate results in Word Search II?
Remove the word from its trie node the first time it is found. Pruning empty trie branches afterward also stops later searches from revisiting finished paths.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
