Solve LeetCode 212: Word Search II in Python with a trie-guided board DFS approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Trie |
| Reusable pattern | trie-guided board DFS |
| Complexity | O(mn·4^L) worst-case time with strong trie pruning and O(total word characters) space |
What the problem is testing
Build a trie of target words and DFS from each board cell, pruning paths absent from the trie and removing words after discovery to avoid duplicates.
Algorithm
- Build a trie of target words and DFS from each board cell, pruning paths absent from the trie and removing words after discovery to avoid duplicates.
- Maintain this invariant: Every DFS path matches the trie prefix represented by its current node and uses each board cell at most once.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
class Solution:
def findWords(self, board, words):
root = {}
for word in words:
node = root
for char in word: node = node.setdefault(char, {})
node["$"] = word
rows, cols, answer = len(board), len(board[0]), []
def search(r, c, parent):
char = board[r][c]
if char not in parent: return
node = parent[char]
word = node.pop("$", None)
if word: answer.append(word)
board[r][c] = "#"
for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#": search(nr, nc, node)
board[r][c] = char
if not node: parent.pop(char)
for r in range(rows):
for c in range(cols): search(r, c, root)
return answerWhy this is correct
The proof follows the maintained state: Every DFS path matches the trie prefix represented by its current node and uses each board cell at most once. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(mn·4^L) worst-case time with strong trie pruning and O(total word characters) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
The same word should be emitted once; restore board cells after backtracking.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 211. Design Add and Search Words Data Structure