← Back to Visualizer Gallery
Traversal · Backtracking + Trie LeetCode 212

Word Search II / prefix tree pruning

Searching for multiple words simultaneously by marching board cells and a Trie in lockstep: prune non-existent prefixes in $O(1)$, collect discovered words, and prune dead leaves from the Trie.

Execution Stage

idle
INVARIANT Trie-Pruning Invariant: The DFS frontier is gated strictly by currNode.children[char]. When node.word != null, capture the word and clear node.word = null to prevent duplicates without a HashSet.
Discovered Words:
Grid Board (4×4)
Trie Prefix Active State
Press Run to trace Trie-guided word search.
0 / 0
Speed

Java · Reference Algorithm

INTERVIEW SCRIPT

How to Present Word Search II to an Interviewer

1. Why Naive LC 79 TLEs

"Running LC 79 independently for $W$ words takes $O(W \cdot M \cdot N \cdot 3^L)$ time, repeatedly traversing identical grid paths for overlapping prefixes like 'oat' and 'oath'. A Trie unifies all searches into a single joint traversal."

2. Lockstep Trie + Grid Walking

"Instead of carrying a string builder and querying a prefix set, we pass the active TrieNode down the DFS stack. If node.children[ch] == null, the entire branch is pruned in $O(1)$."

3. In-Place De-duplication

"Store the completed string directly in node.word at leaf nodes. When found, collect it into the result list and immediately set node.word = null. This eliminates the need for an expensive HashSet."

4. Leaf Pruning Optimization

"When a leaf word is matched and has no further children, we prune it from its parent's children map. Dead branches are pruned so subsequent grid searches skip them instantly."

Word Search II (LC 212) — Backtracking + Trie Prefix sharing · Time $O(M \cdot N \cdot 3^L)$, Space $O(\sum |word|)$.