Tries · Pattern 2 of 3
Trie + backtracking: find many words at once
Put all the words in a trie, then backtrack over the grid while walking the trie at the same time. The moment the current path is not a prefix of any word, stop: that pruning is what makes it fast.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Find every word from a list on a board or in a string
- Checking each word separately would repeat the same search many times
- Paths that can be cut off as soon as no word continues them
The template
static class Node { Node[] next = new Node[26]; String word; } // word is set on end nodes
List<String> findWords(char[][] board, String[] words) {
Node root = new Node();
for (String w : words) {
Node cur = root;
for (char c : w.toCharArray()) {
if (cur.next[c - 'a'] == null) cur.next[c - 'a'] = new Node();
cur = cur.next[c - 'a'];
}
cur.word = w;
}
List<String> res = new ArrayList<>();
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++) dfs(board, r, c, root, res);
return res;
}
void dfs(char[][] b, int r, int c, Node parent, List<String> res) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] == '#') return;
Node node = parent.next[b[r][c] - 'a'];
if (node == null) return; // no word continues this way: prune
if (node.word != null) { res.add(node.word); node.word = null; } // found; never add it twice
char ch = b[r][c];
b[r][c] = '#'; // mark as used on this path
dfs(b, r + 1, c, node, res); dfs(b, r - 1, c, node, res);
dfs(b, r, c + 1, node, res); dfs(b, r, c - 1, node, res);
b[r][c] = ch; // undo
} def find_words(board, words):
root = {}
for w in words: # build the trie; '$' holds the word at its end node
node = root
for c in w:
node = node.setdefault(c, {})
node['$'] = w
rows, cols, res = len(board), len(board[0]), []
def dfs(r, c, parent):
ch = board[r][c]
node = parent.get(ch)
if node is None: # no word continues this way: prune
return
if '$' in node:
res.append(node.pop('$')) # found; never add it twice
board[r][c] = '#' # mark as used on this path
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != '#':
dfs(nr, nc, node)
board[r][c] = ch # undo
for r in range(rows):
for c in range(cols):
dfs(r, c, root)
return res struct Node { Node* next[26] = {}; string word; }; // word is set on end nodes
void dfs(vector<vector<char>>& b, int r, int c, Node* parent, vector<string>& res) {
if (r < 0 || c < 0 || r >= (int)b.size() || c >= (int)b[0].size() || b[r][c] == '#') return;
Node* node = parent->next[b[r][c] - 'a'];
if (!node) return; // no word continues this way: prune
if (!node->word.empty()) { res.push_back(node->word); node->word.clear(); } // never twice
char ch = b[r][c];
b[r][c] = '#'; // mark as used on this path
dfs(b, r + 1, c, node, res); dfs(b, r - 1, c, node, res);
dfs(b, r, c + 1, node, res); dfs(b, r, c - 1, node, res);
b[r][c] = ch; // undo
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Node* root = new Node();
for (auto& w : words) {
Node* cur = root;
for (char c : w) {
if (!cur->next[c - 'a']) cur->next[c - 'a'] = new Node();
cur = cur->next[c - 'a'];
}
cur->word = w;
}
vector<string> res;
for (int r = 0; r < (int)board.size(); r++)
for (int c = 0; c < (int)board[0].size(); c++) dfs(board, r, c, root, res);
return res;
} function findWords(board, words) {
const root = {};
for (const w of words) { // build the trie; '$' holds the word at its end node
let node = root;
for (const c of w) node = node[c] ??= {};
node.$ = w;
}
const rows = board.length, cols = board[0].length, res = [];
const dfs = (r, c, parent) => {
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] === '#') return;
const ch = board[r][c], node = parent[ch];
if (!node) return; // no word continues this way: prune
if (node.$) { res.push(node.$); delete node.$; } // found; never add it twice
board[r][c] = '#'; // mark as used on this path
dfs(r + 1, c, node); dfs(r - 1, c, node); dfs(r, c + 1, node); dfs(r, c - 1, node);
board[r][c] = ch; // undo
};
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) dfs(r, c, root);
return res;
} The variations
-
1Grid search with a trie
Start a DFS from every cell, carrying the trie node for the path so far. Step only to a neighbour whose letter is a child of that node. Each found word is removed from its node, and pruning empty branches makes later searches even faster.
Mistakes to avoid
- Running a separate word search for every word: the trie lets one DFS check all of them together.
- Adding the same word twice when it can be traced along two paths: clear it from the node once found.
- Forgetting to restore the cell after the DFS, so later paths think it is still used.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.