LeetCode #212 Hard

Word Search II

Word Search II is LeetCode 212 (Hard). Given an m × n grid of letters and a list of words, return every word that can be spelled by a path through the grid.

  • A path moves up, down, left or right to a neighbouring cell.
  • A cell can be used at most once within one word.
  • Each word goes into the answer once, in any order.

The grid is at most 12 × 12, but there can be 30,000 words of up to 10 letters, so running a separate grid search for each word is far too slow.

Constraints
  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 12
  • board[i][j] is a lowercase English letter.
  • 1 <= words.length <= 3 * 10⁴
  • 1 <= words[i].length <= 10
  • words[i] consists of lowercase English letters.
  • All the strings of words are unique.
triebacktrackinggrid
Open on LeetCode ↗
02

Intuition

Searching the grid once per word repeats the same walks: every word that starts with ea walks the same e → a cells again. Instead, put all the words in a trie and run one search that walks the grid and the trie together.

  • Shared prefixes: a path in the grid sits on one trie node, and that node stands for every word starting with those letters, so each prefix is walked once.
  • Instant pruning: if the next cell's letter is not a child of the current node, no word continues that way, so the search turns back at once.
  • Reporting: a node that ends a word hands over the word the moment the path reaches it.
How to spot this pattern

Many words searched in the same grid or text, where words share beginnings, points to a trie: one walk covers every word with the current prefix and stops when none fits.

03

Approach

Try it first

Before reading on, decide what the search should know at each cell so it can give up as soon as no word in the list can continue. Then decide how to stop the same word being reported from two different paths.

1

Build a trie of all the words

Insert each word letter by letter and store the whole word at its last node. When a path reaches that node, the word is right there, with no need to rebuild it from the cells.

2

Start a search from every cell

Call dfs(r, c, root) for each cell. Inside, look up the cell's letter among the current node's children; if it is missing, return at once, since no word in the list continues with that letter here.

3

Report a word when its node is reached

Move to the child node. If it holds a word, add the word to the answer and take it off the node. The word is now done, and the node stays in the trie only while longer words still pass through it.

4

Mark the cell while it is on the path

Overwrite the cell with # before trying its four neighbours, and write the letter back afterwards. The mark stops this path from using the cell twice; writing it back makes the cell free again for every other path.

5

Remove branches with nothing left

After the neighbours are done, if the node has no children and no word, delete it from its parent. Once every word under a branch is found, later searches stop at its first letter instead of walking it again, which keeps large inputs inside the time limit.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
▶3 root = {}
▶4 for w in words:
▶5 node = root
▶6 for ch in w:
▶7 node = node.setdefault(ch, {})
▶8 node["$"] = w
▶9 rows, cols = len(board), len(board[0])
▶10 found = []
▶11 
▶12 def dfs(r, c, parent):
▶13 ch = board[r][c]
▶14 node = parent.get(ch)
▶15 if node is None:
▶16 return
▶17 word = node.pop("$", None)
▶18 if word:
▶19 found.append(word)
▶20 board[r][c] = "#"
▶21 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶22 if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] != "#":
▶23 dfs(nr, nc, node)
▶24 board[r][c] = ch
▶25 if not node:
▶26 del parent[ch]
▶27 
▶28 for r in range(rows):
▶29 for c in range(cols):
▶30 dfs(r, c, root)
▶31 return found
easteateatseatsseaseatriefoundtrie built from 3 words
pathempty
foundnone
Every word is inserted letter by letter, and its last node keeps the whole word (shown beside the node). Now one search starts from each cell, walking the grid and the trie together.
easteateatseatsseaseatriefoundstep onto e: e is a prefix → go on
pathe
foundnone
e is the start of at least one word, so mark this cell as used and try its neighbours.
easteateatseatsseaseatriefoundno word goes e then s → turn back
pathe
foundnone
The trie node for e has no child s, so no word continues this way. The search does not step onto this cell.
easteateatseatsseaseatriefoundstep onto a: ea is a prefix → go on
pathea
foundnone
ea is the start of at least one word, so mark this cell as used and try its neighbours.
easteatseatsseaseatriefoundeateat ends here → found
patheat
foundeat
The node for eat holds a word, so it goes into the answer and is taken off the node; no other path can report it again. The search still goes on, because a longer word may pass through here.
easteatsseaseatriefoundeateatseats ends here → found
patheats
foundeat, eats
The node for eats holds a word, so it goes into the answer and is taken off the node; no other path can report it again. The search still goes on, because a longer word may pass through here.
easteatsseaseatriefoundeateatsback from s: nothing left under eats → remove
patheat
foundeat, eats
All neighbours are tried, so the cell gets its letter back. No word is left under eats, so that node is deleted and later searches stop before it.
easteatsseaseatriefoundeateatsback from t: nothing left under eat → remove
pathea
foundeat, eats
All neighbours are tried, so the cell gets its letter back. No word is left under eat, so that node is deleted and later searches stop before it.
easteatsseaseatriefoundeateatsback from a: nothing left under ea → remove
pathe
foundeat, eats
All neighbours are tried, so the cell gets its letter back. No word is left under ea, so that node is deleted and later searches stop before it.
easteatsseaseatriefoundeateatsback from e: nothing left under e → remove
pathempty
foundeat, eats
All neighbours are tried, so the cell gets its letter back. No word is left under e, so that node is deleted and later searches stop before it.
easteatsseaseatriefoundeateatsno word starts with a → skip cell
pathempty
foundeat, eats
The trie root has no child a, so no word can start here.
easteatsseaseatriefoundeateatsstep onto s: s is a prefix → go on
paths
foundeat, eats
s is the start of at least one word, so mark this cell as used and try its neighbours.
easteatsseaseatriefoundeateatsstep onto e: se is a prefix → go on
pathse
foundeat, eats
se is the start of at least one word, so mark this cell as used and try its neighbours.
easteatsseatriefoundeateatsseasea ends here → found
pathsea
foundeat, eats, sea
The node for sea holds a word, so it goes into the answer and is taken off the node; no other path can report it again. The search still goes on, because a longer word may pass through here.
easteatsseatriefoundeateatsseano word goes sea then t → turn back
pathsea
foundeat, eats, sea
The trie node for sea has no child t, so no word continues this way. The search does not step onto this cell.
easteatsseatriefoundeateatsseaback from a: nothing left under sea → remove
pathse
foundeat, eats, sea
All neighbours are tried, so the cell gets its letter back. No word is left under sea, so that node is deleted and later searches stop before it.
easteatsseatriefoundeateatsseaback from e: nothing left under se → remove
paths
foundeat, eats, sea
All neighbours are tried, so the cell gets its letter back. No word is left under se, so that node is deleted and later searches stop before it.
easteatsseatriefoundeateatsseano word goes s then t → turn back
paths
foundeat, eats, sea
The trie node for s has no child t, so no word continues this way. The search does not step onto this cell.
easteatsseatriefoundeateatsseaback from s: nothing left under s → remove
pathempty
foundeat, eats, sea
All neighbours are tried, so the cell gets its letter back. No word is left under s, so that node is deleted and later searches stop before it.
easteatsseatriefoundeateatsseano word starts with t → skip cell
pathempty
foundeat, eats, sea
The trie root has no child t, so no word can start here.
easteatsseatriefoundeateatsseaanswer: eat, eats, sea
pathempty
foundeat, eats, sea
Every cell has been a starting point. Each word was reported once, the moment its last letter was reached.
05

Common pitfalls

Stopping at the first word on a path

✗ Wrong
if word:
    found.append(word)
    return
✓ Right
if word:
    found.append(word)
# keep going to the neighbours

For words = ["eat", "eats"] on [["e","a"],["s","t"]], the path e → a → t finds eat and returns, so the step on to s never happens and eats is missing.

Leaving the word on its node

✗ Wrong
if "$" in node:
    found.append(node["$"])
✓ Right
word = node.pop("$", None)
if word:
    found.append(word)

For board = [["a","b"],["b","a"]] and words = ["ab"], the grid spells ab along four different paths, so the answer lists it four times. Each word must appear once.

Not writing the letter back

✗ Wrong
board[r][c] = "#"
for ...:
    dfs(nr, nc, node)
✓ Right
board[r][c] = "#"
for ...:
    dfs(nr, nc, node)
board[r][c] = ch

For board = [["a","b"]] and words = ["ab", "ba"], the search from a finds ab and leaves both cells as #. The search from b then sees no letters at all, so ba is never found.

06

Edge cases

No word can start anywhere, e.g. words = ["xyz"]

Every cell fails the first lookup at the root, so the whole search is m × n dictionary lookups and returns [].

07

Complexity

Time
O(m·n·4·3^(L−1))
Space
O(W·L)
L is the longest word (at most 10) and W the number of words. Each start cell begins paths of at most L cells: 4 choices for the first step, then at most 3, because a path never steps back onto its own cells. Building the trie reads every letter once, O(W·L), and the trie holds at most W·L nodes. The recursion is at most L deep.
08

Word Search II FAQ

Why is a trie needed here when Word Search does not need one?

Word Search (LeetCode 79) looks for one word, so plain backtracking is enough. Here up to 30,000 words would each need their own full search. The trie lets one search serve every word that shares the current prefix, and lets it stop the moment no word fits.

Is Word Search II the same as Word Boggle?

Almost. In Word Boggle a path may also step diagonally, so each cell has up to 8 neighbours instead of 4. The trie and backtracking stay the same; only the list of directions grows.

Why not keep the words in a hash set and test every path?

A set answers only "is this exact string a word?", not "does any word start like this?". Without that second answer the search cannot tell when to give up, so it walks every path of up to 10 cells from every cell, millions of paths on a 12 × 12 grid.