BacktrackingLeetCode 212

Lesson 49 of 76

Word Search II

Find every word from a list that can be traced through adjacent cells of a letter grid.

Watch on YouTube

Lesson notes

Try it before you watch

Restate the problem in your own words, list the edge cases, and sketch a solution with its running time. Then play the video and compare.

Reveal the key idea

Put the words in a trie and run one DFS from every cell that follows trie edges, collecting words at end nodes and pruning branches that are exhausted.

Pattern: Backtracking. Build a candidate one choice at a time and undo the choice when it cannot lead to a solution.

Complexity

Cost of the standard optimal approach for Word Search II
Measure Bound
Time O(m · n · 4 · 3^(L−1)) in the worst case
Extra space O(total characters in the word list)

Walkthroughs often start from a simpler approach first; aim to reach these bounds. New to Big-O? Read understanding algorithmic complexity.

More backtracking practice