212. Word Search II
Asked at 19Amazon52Microsoft42Google34Apple30Meta24Bloomberg14Uber70Snowflake90Cisco84Two Sigma84Zoom78Airbnb66Aurora62TikTok58Snap55Wix52DoorDash41Visa39Oracle35
Problem
Given an m×n board of letters and a list of words, return every word that can be traced on the board through horizontally or vertically adjacent cells, using each cell at most once per word.
Example: board = ["oaan","etae","ihkr","iflv"], words = ["oath","pea","eat","rain"] → ["eat","oath"]
Constraints: board up to 12 × 12; up to 3·10⁴ words of length ≤ 10.
Put all words in a trie, then DFS from every cell following the trie — one traversal finds all words. Store the full word at its end node; clear it after finding (dedupe) and prune empty branches.
board o a a n trie of {oath, pea, eat, rain}
e t a e DFS from 'o': o -> a -> t -> h ✓ "oath"
i h k r DFS from 'e': e -> a -> t ✓ "eat"
i f l v
Complexity: O(cells · 4 · 3^(L−1)) worst case, heavily pruned in practice.
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
R, C, res = len(board), len(board[0]), []
def dfs(r, c, parent):
ch = board[r][c]
node = parent[ch]
if "$" in node:
res.append(node.pop("$"))
board[r][c] = "#"
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and board[nr][nc] in node:
dfs(nr, nc, node)
board[r][c] = ch
if not node:
parent.pop(ch) # prune exhausted branch
for r in range(R):
for c in range(C):
if board[r][c] in root:
dfs(r, c, root)
return res
b = [list("oaan"), list("etae"), list("ihkr"), list("iflv")]
assert sorted(Solution().findWords(b, ["oath", "pea", "eat", "rain"])) == ["eat", "oath"]
assert Solution().findWords([["a", "b"], ["c", "d"]], ["abcb"]) == []
assert Solution().findWords([["a"]], ["a"]) == ["a"]
assert sorted(Solution().findWords([["a", "b"], ["c", "d"]], ["ab", "cb", "ad", "bd", "ac", "ca", "da", "bc", "db", "adcb", "dabc", "abb", "acb"])) == ['ab', 'ac', 'bd', 'ca', 'db']
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 n = root;
for (char c : w.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.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;
}
private 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;
char ch = b[r][c];
Node n = parent.next[ch - 'a'];
if (n == null) return;
if (n.word != null) { res.add(n.word); n.word = null; }
b[r][c] = '#';
dfs(b, r + 1, c, n, res); dfs(b, r - 1, c, n, res);
dfs(b, r, c + 1, n, res); dfs(b, r, c - 1, n, res);
b[r][c] = ch;
}
}
type trieNode struct {
next [26]*trieNode
word string // set at the node where a word ends
kids int // live children, for pruning
}
func findWords(board [][]byte, words []string) []string {
root := &trieNode{}
for _, w := range words {
node := root
for i := 0; i < len(w); i++ {
c := w[i] - 'a'
if node.next[c] == nil {
node.next[c] = &trieNode{}
node.kids++
}
node = node.next[c]
}
node.word = w
}
R, C, res := len(board), len(board[0]), []string{}
var dfs func(r, c int, parent *trieNode)
dfs = func(r, c int, parent *trieNode) {
ch := board[r][c]
node := parent.next[ch-'a']
if node.word != "" {
res = append(res, node.word)
node.word = "" // report each word once
}
board[r][c] = '#'
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := r+d[0], c+d[1]
if nr >= 0 && nr < R && nc >= 0 && nc < C && board[nr][nc] != '#' && node.next[board[nr][nc]-'a'] != nil {
dfs(nr, nc, node)
}
}
board[r][c] = ch
if node.kids == 0 && node.word == "" { // prune an exhausted branch
parent.next[ch-'a'] = nil
parent.kids--
}
}
for r := 0; r < R; r++ {
for c := 0; c < C; c++ {
if root.next[board[r][c]-'a'] != nil {
dfs(r, c, root)
}
}
}
return res
}