Home
DSA Patterns
Trie
Word Search II
Word Search II (LeetCode 212)
Word Search II (LeetCode 212): find every word from a list on a letter grid with one backtracking DFS per cell, guided by a trie of the words.
Problem Understanding
Word Search II: given an m × n grid of letters and a list of words, return every word that can be spelled by a path of horizontally or vertically adjacent cells, using each cell at most once per word.
Example: on the board oaan; etae; ihkr; iflv with words oath, pea, eat, rain, the answer is oath and eat.
Attempt 1: Word Search Once Per Word
Run the single-word Word Search for each word. It works, but with many words that share prefixes, like oat, oath and oaths, the same paths are walked again and again. The grid search should check every word in a single pass.
The Intuition: Let a Trie Steer the DFS
Put every word in a trie. Then run one backtracking DFS from each cell, carrying a pointer into the trie:
- At a cell, move to the trie child for its letter. If there is no such child, no word continues this way: stop the branch immediately.
- If that trie node ends a word, record the word and clear the mark so it is not added twice.
- Mark the cell
#, try its unvisited neighbours with the child node, then write the letter back.
The trie turns "is this path the start of any word?" into a single lookup, which is what prunes the search.
Word Search II Visualization
WORDS: OATH, PEA, EAT, RAIN
BUILD THE TRIE
Prefix
:
Found
0
words found
None yet
Put every word in a trie: "oath", "pea", "eat", "rain"
Next
Start a DFS at (0, 0), 'o', from the trie root
Board
Words
Every cell starts a DFS in turn. Cells on the current path show #, linked in path order, and the prefix they spell is shown beside the board. A cell turns red the moment no word continues with its letter, and green when a word ends there.
Word Search II Dry Run
Board: oaan; etae; ihkr; iflv. Words: oath, pea, eat, rain
| Start | Path | Result |
|---|---|---|
(0,0) o |
o → a → t → h | found oath |
(0,1) a |
a |
no word starts with a: stop |
(1,0) e |
e → (no a next to it) |
stop |
(1,3) e |
e → a → t | found eat |
(2,3) r |
r → (no a next to it) |
stop: rain is not on the board |
pea is never started: there is no p on the board.
Word Search II LeetCode Solution
A trie of the words, and a backtracking DFS from every cell that follows it.
Word Search II Code
1var findWords = function(board, words) {2 const root = {};3 for (const w of words) {4 let node = root;5 for (const ch of w) node = node[ch] ??= {};6 node.$ = w;7 }8 const rows = board.length, cols = board[0].length, found = [];9 const dfs = (r, c, node) => {10 const ch = board[r][c];11 const nxt = node[ch];12 if (!nxt) return;13 if (nxt.$) {14 found.push(nxt.$);15 delete nxt.$;16 }17 board[r][c] = '#';18 for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {19 const nr = r + dr, nc = c + dc;20 if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') dfs(nr, nc, nxt);21 }22 board[r][c] = ch;23 };24 for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) dfs(r, c, root);25 return found;26};
Word Search II in Python, Java, C++, TypeScript and C
Word Search II in Python
class Solution:
def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
root = {}
for w in words:
node = root
for ch in w:
node = node.setdefault(ch, {})
node['$'] = w
rows, cols, found = len(board), len(board[0]), []
def dfs(r, c, node):
ch = board[r][c]
if ch not in node:
return
nxt = node[ch]
if '$' in nxt:
found.append(nxt.pop('$'))
board[r][c] = '#'
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != '#':
dfs(nr, nc, nxt)
board[r][c] = ch
for r in range(rows):
for c in range(cols):
dfs(r, c, root)
return foundWord Search II in Java
class Solution {
private static class Node { Node[] next = new Node[26]; String word; }
public List<String> findWords(char[][] board, String[] words) {
Node root = new Node();
for (String w : words) {
Node node = root;
for (char ch : w.toCharArray()) {
if (node.next[ch - 'a'] == null) node.next[ch - 'a'] = new Node();
node = node.next[ch - 'a'];
}
node.word = w;
}
List<String> found = new ArrayList<>();
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++)
dfs(board, r, c, root, found);
return found;
}
private void dfs(char[][] board, int r, int c, Node node, List<String> found) {
char ch = board[r][c];
if (node.next[ch - 'a'] == null) return;
Node nxt = node.next[ch - 'a'];
if (nxt.word != null) {
found.add(nxt.word);
nxt.word = null;
}
board[r][c] = '#';
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < board.length && nc >= 0 && nc < board[0].length && board[nr][nc] != '#') dfs(board, nr, nc, nxt, found);
}
board[r][c] = ch;
}
}Word Search II in C++
class Solution {
struct Node { Node* next[26] = {}; string word; };
vector<string> found;
void dfs(vector<vector<char>>& board, int r, int c, Node* node) {
char ch = board[r][c];
if (!node->next[ch - 'a']) return;
Node* nxt = node->next[ch - 'a'];
if (!nxt->word.empty()) {
found.push_back(nxt->word);
nxt->word.clear();
}
board[r][c] = '#';
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (auto& d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < (int)board.size() && nc >= 0 && nc < (int)board[0].size() && board[nr][nc] != '#')
dfs(board, nr, nc, nxt);
}
board[r][c] = ch;
}
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Node* root = new Node();
for (auto& w : words) {
Node* node = root;
for (char ch : w) {
if (!node->next[ch - 'a']) node->next[ch - 'a'] = new Node();
node = node->next[ch - 'a'];
}
node->word = w;
}
for (int r = 0; r < (int)board.size(); r++)
for (int c = 0; c < (int)board[0].size(); c++)
dfs(board, r, c, root);
return found;
}
};Word Search II in TypeScript
class TrieNode {
next = new Map<string, TrieNode>();
word: string | null = null;
}
function findWords(board: string[][], words: string[]): string[] {
const root = new TrieNode();
for (const w of words) {
let node = root;
for (const ch of w) {
if (!node.next.has(ch)) node.next.set(ch, new TrieNode());
node = node.next.get(ch)!;
}
node.word = w;
}
const rows = board.length, cols = board[0].length, found: string[] = [];
const dfs = (r: number, c: number, node: TrieNode): void => {
const ch = board[r][c];
const nxt = node.next.get(ch);
if (!nxt) return;
if (nxt.word !== null) {
found.push(nxt.word);
nxt.word = null;
}
board[r][c] = '#';
for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] !== '#') dfs(nr, nc, nxt);
}
board[r][c] = ch;
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) dfs(r, c, root);
return found;
}Word Search II in C
typedef struct Node { struct Node* next[26]; char* word; } Node;
static void dfs(char** board, int rows, int cols, int r, int c, Node* node, char** found, int* count) {
char ch = board[r][c];
Node* nxt = node->next[ch - 'a'];
if (!nxt) return;
if (nxt->word) {
found[(*count)++] = nxt->word;
nxt->word = NULL;
}
board[r][c] = '#';
int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int k = 0; k < 4; k++) {
int nr = r + dirs[k][0], nc = c + dirs[k][1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] != '#') dfs(board, rows, cols, nr, nc, nxt, found, count);
}
board[r][c] = ch;
}
char** findWords(char** board, int boardSize, int* boardColSize, char** words, int wordsSize, int* returnSize) {
Node* root = calloc(1, sizeof(Node));
for (int i = 0; i < wordsSize; i++) {
Node* node = root;
for (char* p = words[i]; *p; p++) {
if (!node->next[*p - 'a']) node->next[*p - 'a'] = calloc(1, sizeof(Node));
node = node->next[*p - 'a'];
}
node->word = words[i];
}
char** found = malloc(wordsSize * sizeof(char*));
*returnSize = 0;
for (int r = 0; r < boardSize; r++)
for (int c = 0; c < boardColSize[0]; c++)
dfs(board, boardSize, boardColSize[0], r, c, root, found, returnSize);
return found;
}Edge Cases & Common Mistakes
- The same word on two paths: clear the word-end mark when it is found, or the word appears twice in the answer.
- Reusing a cell: mark it
#before exploring and write the letter back afterwards, exactly as in Word Search. - Words that are prefixes of other words:
oatandoathare both recorded on the same walk, because finding a word does not stop the DFS. - Letters not on the board: words with them are never started, at no cost.
Summary
Word Search II is Word Search with a trie in place of a single target word. One backtracking DFS per cell follows the trie, stops as soon as no word shares the current prefix, and collects every word whose end it reaches.
More practice: DSA interview questions with answers · patterns cheat sheet
