Words Traced Through a Letter Board
Trees & GraphsAuto-graded · 16 test casesLast updated
Find every dictionary word that can be traced through orthogonally adjacent cells of a letter board without reusing a cell, using backtracking guided by a prefix tree.
Words Traced Through a Letter Board
You are given a rectangular board of lowercase letters and a list of candidate words. Work out which candidates can be spelled by walking across the board.
A word can be spelled if there is a path of cells such that:
- the letters along the path, in order, spell the word exactly;
- each step moves to a cell directly above, below, left, or right of the current cell (diagonal steps are not allowed);
- no cell appears more than once in the path for that word.
Different words are checked independently, so a cell used by one word may be used again by another.
Task
Implement collect_grid_words(board, candidates), which returns every candidate word that can be spelled on the board.
Output rules
- Each word appears at most once in the result, even if it appears several times in
candidates. - The result is sorted in ascending lexicographic order.
- If no word can be spelled, return an empty list.
- If the board is empty (no rows or no columns) or
candidatesis empty, return an empty list. - An empty-string candidate is never included.
- Do not modify the input board.
Constraints
- The board has
Mrows andNcolumns, with1 <= M, N <= 10(an empty board must still be handled gracefully). - All rows have the same length, and each cell holds a single character.
candidateshas at most 1000 words.- Each word has length at most 10.
Examples
Example 1
Input: collect_grid_words([['a', 'b'], ['c', 'd']], ['ab', 'ad', 'ac'])
Output: ['ab', 'ac']
Example 2
Input: collect_grid_words([['a', 'e'], ['f', 'g']], ['aeg', 'af'])
Output: ['aeg', 'af']
Hints
Hint 1
Running a separate board search for every word repeats a lot of work when words share a beginning, such as 'oat' and 'oath'. Think about a structure that stores all words by their prefixes.
Hint 2
Build a prefix tree from the candidates, then run a depth-first search from every cell, moving only into neighbors whose letter continues a prefix in the tree. Temporarily mark the current cell as used and restore it when you backtrack.
Hint 3
Record a word when the current tree node ends one, and keep exploring since longer words may share it as a prefix. Store results in a set (or remove the word from the tree once found) to avoid duplicates, and sort at the end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Searching the board once per word repeats work whenever words share a prefix. Instead, store all candidates in a prefix tree (trie) and search the board once, walking the board and the trie together.
- Build the trie. Insert each distinct non-empty candidate. The node at the end of a word stores that word.
- DFS from every cell. At a cell, look up its letter among the children of the current trie node. If there is no such child, no candidate continues this way, so stop.
- Record words. If the node reached stores a word, add it to the results and remove it from the node so it cannot be reported twice. Keep exploring, since longer words may extend it.
- Avoid cell reuse. Mark the current cell as used (replace it with a sentinel in a copy of the board), recurse into the four orthogonal neighbors that are not used, then restore the cell on backtrack.
- Prune. After exploring, if the trie node has no children and no stored word, delete it from its parent. This shrinks the search as words are found.
- Sort the collected words.
Why it is correct
- Completeness: every valid path starts at some cell, and every prefix of the spelled word exists in the trie, so the DFS never cuts a valid path. Pruning only removes nodes with no remaining words beneath them.
- Soundness: a word is recorded only when the DFS reaches its terminal node, meaning the path spelled it exactly through adjacent, unused cells.
- No duplicates: candidates are deduplicated, and results are collected in a set.
- Backtracking restores each cell, so different words and different starting cells are independent.
Complexity
Let L be the maximum word length and S the total number of characters across all candidates.
- Time: building the trie is
O(S). The search is at mostO(M * N * 4 * 3^(L-1))in the worst case, since after the first step at most 3 neighbors are unused. The trie cuts this down heavily in practice. - Space:
O(S)for the trie, plusO(M * N)for the board copy andO(L)recursion depth.
Reference solution
from typing import List
def collect_grid_words(board: List[List[str]], candidates: List[str]) -> List[str]:
if not board or not board[0] or not candidates:
return []
# Prefix tree as nested dicts; the key None stores a completed word.
root = {}
for word in set(candidates):
if not word:
continue
node = root
for ch in word:
node = node.setdefault(ch, {})
node[None] = word
grid = [list(row) for row in board]
rows, cols = len(grid), len(grid[0])
found = set()
def explore(r, c, parent):
ch = grid[r][c]
node = parent.get(ch)
if node is None:
return
word = node.pop(None, None)
if word is not None:
found.add(word)
grid[r][c] = None # mark as used on the current path
if r > 0 and grid[r - 1][c] is not None:
explore(r - 1, c, node)
if r + 1 < rows and grid[r + 1][c] is not None:
explore(r + 1, c, node)
if c > 0 and grid[r][c - 1] is not None:
explore(r, c - 1, node)
if c + 1 < cols and grid[r][c + 1] is not None:
explore(r, c + 1, node)
grid[r][c] = ch # restore on backtrack
if not node: # nothing left below this prefix; prune it
del parent[ch]
for r in range(rows):
for c in range(cols):
if not root:
return sorted(found)
explore(r, c, root)
return sorted(found)