hardTrieBacktrackingTrie

Word Search II

hardTime: O(m * n * 4^L)Space: O(N * L)

Recognize the pattern

find all words from dictionary in a gridmultiple word search simultaneouslytrie + backtracking

Brute force idea

The naive version of Word Search II sounds like this: Run Word Search I for each word independently. Redundant because many words share prefixes. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The deeper shift in Word Search II is this: Build a trie from all words. DFS from each cell, following trie branches. If you reach a trie node marked as a word end, record it. The trie prunes branches that don't match any word prefix. but with massive pruning. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Word Search II is one steady idea: The trie lets you check ALL words simultaneously as you explore the grid. If no word in the trie starts with the current path, stop exploring — no word can possibly match. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

One easy way to drift off course in Word Search II is this: Not removing found words from the trie — if you don't, you may find the same word multiple times from different starting cells. Decrement the word count or prune the trie branch after finding. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trie Pattern