Spell Words Along Connected Paths in a Letter Grid
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests backtracking DFS with trie-based pruning to find all words from a large list that can be traced through edge-adjacent, non-repeating cells in a 2-D letter grid.
You have an m x n grid of lowercase letters and a list of words to look up.
A word is traceable in the grid if you can find a sequence of cells whose letters match the word character by character, where every consecutive pair of cells shares an edge (up, down, left, or right), and no cell appears more than once in the same sequence.
Return all traceable words in ascending lexicographic order. If no word can be traced, return an empty list.
Rules
- Two cells are adjacent only if they share an edge. Diagonal neighbours do not count.
- Within the path for a single word, every cell must be distinct. Separate words may pass through the same cells.
- If a word appears more than once in the input list, include it at most once in the output.
Constraints
1 <= m, n <= 12, wherem = len(board)andn = len(board[i])for all rowsi- Every
board[i][j]is a single lowercase English letter ('a'–'z'). 1 <= len(words) <= 300001 <= len(words[i]) <= 10, and every word consists of lowercase English letters.- The output must be sorted in ascending lexicographic (alphabetical) order.
Examples
Example 1
Input: locate_words([['c', 'a', 't'], ['r', 'o', 's'], ['e', 'd', 'g']], ['cat', 'cot', 'rod', 'red', 'dog', 'oat'])
Output: ['cat', 'oat', 'red', 'rod']
Example 2
Input: locate_words([['a', 'b'], ['c', 'd']], ['abdc', 'aba', 'abcd', 'a', 'a'])
Output: ['a', 'abdc']
Example 3
Input: locate_words([['a', 'a']], ['aaa'])
Output: []
Hints
Hint 1
Start with the single-word case: try every cell as a starting point and use backtracking DFS, temporarily marking each visited cell so it is not reused. Restore the cell when you backtrack.
Hint 2
Running an independent search per word is too slow for 30,000 words. Insert all words into a prefix tree (trie) first, then walk the grid and the trie together in one shared pass — a grid path that matches no trie prefix can be abandoned immediately.
Hint 3
Once a word is found, remove its end-marker from the trie so it is never reported twice. After backtracking, if a trie node is completely empty, delete it from its parent — this prunes dead branches and speeds up later searches.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — Single-word backtracking
For one word, try every grid cell as a potential starting position. From a matching start cell, run a depth-first search: confirm the current letter matches, mark the cell with a placeholder ('#') so it cannot be reused, recurse into each of the four edge neighbours for the next letter, then restore the cell when returning. This is standard backtracking.
The cost for one word of length L is roughly O(m·n · 4 · 3^(L−1)): m·n starting points, one choice of four at the first step, and at most three at every subsequent step (you cannot re-enter the cell you came from). For a 12×12 board and L = 10 that is about 11 million steps per word — far too slow across 30,000 words.
Step 2 — Search all words at once with a trie
Insert every distinct word into a prefix tree (trie) where each node is a dict of child letters. A sentinel key '$' at a node stores the complete word that ends there.
Now run one DFS pass over the grid. At each cell, instead of checking against a single target word, check whether the cell's letter is a child of the current trie node. If yes, descend into that trie node and continue. If no word in the trie starts with this prefix, the search stops immediately.
Because all words share the trie, paths with common prefixes — say "rod" and "red" both starting with r — are explored together in a single traversal rather than twice.
Pruning tricks
Pop on find. When a '$' entry is reached, remove it with node.pop('$', None). The word is recorded exactly once regardless of how many paths lead there, and no separate "seen" set is needed. Duplicate words in the input are handled upfront with set(words).
Delete empty branches. After a DFS call returns, if the trie node is now empty (no remaining words, no children), delete it from its parent. Future searches skip that branch entirely. This is especially valuable on grids dense with repeated letters, where the same prefix would otherwise be re-explored many times.
Correctness
Soundness. The DFS only steps between edge-adjacent cells and never enters a cell marked '#', so every path is a valid non-repeating sequence of adjacent cells. Reaching a '$' node means the path letters spell exactly that word.
Completeness. If word w has a valid tracing c1, c2, …, cL, the outer loop launches a DFS from c1. At every step the next cell is unvisited and its letter is a trie child, so the DFS can follow the tracing all the way to the end node.
Pruning safety. A branch is deleted only when it holds no remaining words. Everything reachable through it has already been found, so nothing is lost.
Complexity
Let W be the total character count across all words (≤ 300,000) and L ≤ 10 the maximum word length.
- Time:
O(W)to build the trie.O(m·n · 4 · 3^(L−1))for the grid search, heavily reduced in practice by trie and branch pruning.O(k log k · L)to sortkfound words. - Space:
O(W)for the trie,O(m·n)for the board copy,O(L)recursion depth.
Edge cases
- Duplicate words in input — deduplicated with
set(words)before trie construction. - Single-letter words — matched the moment the root's child is visited; no neighbours are explored.
- Words requiring a cell twice (e.g.,
"aaa"on[["a","a"]]) — the'#'marking prevents reuse, so these are never traced. - Diagonal-only paths — only the four edge neighbours are checked, so diagonal paths are never followed.
- Words longer than
m·n— the DFS exhausts unvisited cells before matching all letters; such words are simply never found. - Words that are prefixes of other words — the
'$'sentinel sits alongside child-letter keys in the same node. Popping it does not stop the DFS from continuing to longer words through the remaining children. - No traceable words — returns
[].
Reference solution
from typing import List
def locate_words(board: List[List[str]], words: List[str]) -> List[str]:
# Build a trie from the distinct input words.
# Each node is a plain dict; '$' maps to the full word string at the end of a word.
root: dict = {}
for w in set(words):
node = root
for ch in w:
node = node.setdefault(ch, {})
node['$'] = w
m, n = len(board), len(board[0])
# Work on a copy so the caller's board is never mutated.
grid = [row[:] for row in board]
found: List[str] = []
def dfs(i: int, j: int, parent: dict) -> None:
ch = grid[i][j]
node = parent[ch]
# If a complete word ends here, record it and remove the marker so
# it cannot be reported again even if another path reaches this node.
word = node.pop('$', None)
if word is not None:
found.append(word)
# Explore neighbours only while longer words still exist under this node.
if node:
grid[i][j] = '#' # mark cell as occupied on the current path
if i > 0 and grid[i - 1][j] in node:
dfs(i - 1, j, node)
if i + 1 < m and grid[i + 1][j] in node:
dfs(i + 1, j, node)
if j > 0 and grid[i][j - 1] in node:
dfs(i, j - 1, node)
if j + 1 < n and grid[i][j + 1] in node:
dfs(i, j + 1, node)
grid[i][j] = ch # backtrack: restore the cell
# Prune: if this node is now empty it holds no more words,
# so remove it from its parent to avoid revisiting.
if not node:
del parent[ch]
for i in range(m):
for j in range(n):
if grid[i][j] in root:
dfs(i, j, root)
found.sort()
return found