Word Search II
Hard · Tries
Jump to codeGiven a rectangular letter board and a list of distinct nonempty words, return those that can be traced using horizontal or vertical neighbors. A cell cannot be reused within one word.
Examples
Example 1
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]] words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Example 2
board = [["a","b"],["c","d"]] words = ["abcb"]
Output: []
Constraints
- 1 <= board.length, board[i].length <= 12
- board[i] consists only of lowercase English letters.
- 1 <= words.length <= 30,000
- 1 <= words[i].length <= 10
- words[i] consists only of lowercase English letters.
- All strings within words are distinct.
Need a hint?
Share work between words with the same prefix.
Real trie interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Design autocomplete with TrieGoogle
- Implement Prefix Match FilterDatadog
- Implement trie-based autocompletePinterest
Solution approach
Build a trie from the words, then start a backtracking search at each cell. Follow only edges that exist in the trie, temporarily mark each visited cell, and restore it on return. Record terminal words in a set or clear their terminal marker to avoid duplicate output.
Complexity
O(total word characters + mn·4·3^(L−1)) loose worst-case time for longest word L; O(total word characters + L) auxiliary space.
Python reference solution
def findWords(board, words):
trie = {}
for word in words:
node = trie
for char in word:
node = node.setdefault(char, {})
node['$'] = word
answer = []
rows, cols = len(board), len(board[0]) if board else 0
def search(row, col, parent):
char = board[row][col]
if char not in parent:
return
node = parent[char]
word = node.pop('$', None)
if word is not None:
answer.append(word)
board[row][col] = '#'
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
r, c = row + dr, col + dc
if 0 <= r < rows and 0 <= c < cols:
search(r, c, node)
board[row][col] = char
if not node:
del parent[char]
for row in range(rows):
for col in range(cols):
search(row, col, trie)
return answer
JavaScript solution
function findWords(board, words) {
const root = {children: new Map(), word: null};
for (const word of words) {
let node = root;
for (const c of word) {
if (!node.children.has(c)) node.children.set(c, {children: new Map(), word: null});
node = node.children.get(c);
}
node.word = word;
}
const answer = [], rows = board.length, cols = rows ? board[0].length : 0;
function search(row, col, parent) {
if (row < 0 || row >= rows || col < 0 || col >= cols) return;
const c = board[row][col], node = parent.children.get(c);
if (!node) return;
if (node.word !== null) { answer.push(node.word); node.word = null; }
board[row][col] = '#';
search(row + 1, col, node); search(row - 1, col, node);
search(row, col + 1, node); search(row, col - 1, node);
board[row][col] = c;
if (node.word === null && node.children.size === 0) parent.children.delete(c);
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) search(row, col, root);
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public String[] findWords(char[][] board, String[] words) {
TrieNode root = new TrieNode();
for (String word : words) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (node.children[i] == null) node.children[i] = new TrieNode();
node = node.children[i];
}
node.word = word;
}
List<String> answer = new ArrayList<>();
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) search(board, row, col, root, answer);
}
return answer.toArray(new String[0]);
}
private static class TrieNode {
TrieNode[] children = new TrieNode[26];
String word;
}
private void search(char[][] board, int row, int col, TrieNode parent, List<String> answer) {
if (row < 0 || row >= board.length || col < 0 || col >= board[row].length) return;
char c = board[row][col];
if (c == '#' || parent.children[c - 'a'] == null) return;
TrieNode node = parent.children[c - 'a'];
if (node.word != null) { answer.add(node.word); node.word = null; }
board[row][col] = '#';
search(board, row + 1, col, node, answer); search(board, row - 1, col, node, answer);
search(board, row, col + 1, node, answer); search(board, row, col - 1, node, answer);
board[row][col] = c;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<string> findWords(vector<vector<char>> &board, vector<string> &words) {
vector<TrieNode> nodes(1);
for (int w = 0; w < (int)words.size(); w++) {
int node = 0;
for (char c : words[w]) {
int i = c - 'a';
if (nodes[node].children[i] == -1) {
int next = nodes.size();
nodes.emplace_back();
nodes[node].children[i] = next;
}
node = nodes[node].children[i];
}
nodes[node].word = w;
}
vector<string> answer;
int rows = board.size(), cols = rows ? board[0].size() : 0;
function<void(int, int, int)> search = [&](int row, int col, int parent) {
if (row < 0 || row >= rows || col < 0 || col >= cols || board[row][col] == '#') return;
char c = board[row][col];
int node = nodes[parent].children[c - 'a'];
if (node == -1) return;
if (nodes[node].word != -1) {
answer.push_back(words[nodes[node].word]);
nodes[node].word = -1;
}
board[row][col] = '#';
search(row + 1, col, node); search(row - 1, col, node);
search(row, col + 1, node); search(row, col - 1, node);
board[row][col] = c;
};
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) search(row, col, 0);
}
return answer;
}
struct TrieNode {
array<int, 26> children;
int word = -1;
TrieNode() { children.fill(-1); }
};
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
[
"o",
"a",
"a",
"n"
],
[
"e",
"t",
"a",
"e"
],
[
"i",
"h",
"k",
"r"
],
[
"i",
"f",
"l",
"v"
]
],
[
"oath",
"pea",
"eat",
"rain"
]
][ "eat", "oath" ]
[
[
[
"a",
"b"
],
[
"c",
"d"
]
],
[
"abcb"
]
][]
[
[
[
"a"
]
],
[
"a",
"b"
]
][ "a" ]
[
[
[
"a",
"b",
"c"
],
[
"d",
"e",
"f"
],
[
"g",
"h",
"i"
]
],
[
"abe",
"cfi",
"adg",
"aei"
]
][ "abe", "adg", "cfi" ]
[
[
[
"a",
"a"
],
[
"a",
"a"
]
],
[
"aa",
"aaa",
"aaaa"
]
][ "aa", "aaa", "aaaa" ]
Drafts are saved per language in this browser when storage is available.