Dictionary Words Hidden in a Letter Grid
Trees & GraphsAuto-graded · 18 test casesLast updated
Find every dictionary word that can be traced through adjacent, non-repeating cells of a letter grid, which rewards sharing prefixes across words instead of searching per word.
You are given a rectangular grid of lowercase letters and a list of lowercase words. Write a function that returns every word from the list that can be traced in the grid.
A word is traceable if you can pick a starting cell and then repeatedly step to a horizontally or vertically adjacent cell so that the letters you visit, in order, spell the word. Diagonal steps are not allowed. A single cell cannot be used twice within the spelling of one word. Different words may reuse the same cells.
Input
grid: a list ofmrows, each a list ofnsingle-character lowercase strings.dictionary: a list of lowercase strings. It may contain duplicates.
Output
A list of strings containing each traceable word exactly once, even if the word appears several times in dictionary or can be traced along several different paths. The order of the returned words does not matter. If nothing can be traced, return an empty list.
The dictionary can be large, so checking each word with its own full grid search is too slow. Aim for a solution that shares work between words with common prefixes.
Constraints
1 <= m, n <= 121 <= len(dictionary) <= 300001 <= len(dictionary[i]) <= 10- Every word and every grid cell contains only lowercase English letters.
Examples
Example 1
Input: search_grid_dictionary([['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v']], ['oath', 'pea', 'eat', 'rain'])
Output: ['oath', 'eat']
Example 2
Input: search_grid_dictionary([['a', 'b'], ['c', 'd']], ['ab', 'ac', 'bd', 'abcd'])
Output: ['ac', 'ab', 'bd']
Hints
Hint 1
Searching the grid once per word repeats the same prefix walks many times. Think about a structure that stores all the words together so shared prefixes are stored once.
Hint 2
Build a prefix tree from the dictionary, then run a single backtracking DFS from every cell while descending the prefix tree in step with the grid. Stop as soon as the current letter has no matching child.
Hint 3
To avoid duplicates, clear the end-of-word marker once its word is reported. To speed things up, delete prefix-tree nodes that have no children and no word left after exploring them.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Checking each word separately repeats a lot of work, because words such as "oath" and "oat" share the prefix "oa". Instead, we flip the loop:
- Insert all dictionary words into a trie (prefix tree). Each word's final node stores the word itself under a special key.
- Start a backtracking DFS from every grid cell. The DFS walks the grid and the trie together. Each step into a cell must match a child of the current trie node, otherwise no word continues along this path and we stop immediately.
- When we reach a node that holds a word, we record it and remove that marker. This guarantees each word is reported only once, without needing a separate result set.
- A
visitedmatrix prevents reusing a cell within the current path. It is set before recursing and cleared afterwards (backtracking). - After exploring a node, if it has no children and no stored word, we delete it from its parent. Dead branches then cost nothing in later searches.
Why it is correct
- Soundness: the DFS only follows grid letters that match trie edges, moves only to orthogonal neighbours, and never reuses a cell on the current path. So any recorded word is spelled by a valid path.
- Completeness: the DFS starts from every cell and tries all four neighbours. It only cuts a path when the trie has no matching child, which cannot happen along the path of a word that is still unreported. Pruning only removes nodes whose subtrees contain no unreported words, so it never hides a word we still need to find.
- Uniqueness: each end marker is removed on first discovery, and duplicate dictionary entries merge into a single trie path.
- A word that is a prefix of another (for example
"oa"and"oath") is handled correctly. Removing the marker for"oa"leaves its children in place, so"oath"can still be found.
Complexity
Let W be the number of words, L the maximum word length (at most 10), and m x n the grid size.
- Building the trie takes O(W * L) time and space.
- The search is bounded by O(m * n * 4 * 3^(L-1)), because the depth is at most
Land after the first step each move has at most 3 choices. In practice the trie cuts most branches immediately and pruning shrinks it further. - Extra space is O(m * n) for
visited, plus O(L) recursion depth.
Reference solution
from typing import List
def search_grid_dictionary(grid: List[List[str]], dictionary: List[str]) -> List[str]:
if not grid or not grid[0] or not dictionary:
return []
rows, cols = len(grid), len(grid[0])
# Trie of nested dicts; the key None stores the complete word at its end node.
root = {}
for word in dictionary:
node = root
for ch in word:
node = node.setdefault(ch, {})
node[None] = word
found = []
visited = [[False] * cols for _ in range(rows)]
def dfs(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.append(word)
visited[r][c] = True
if r > 0 and not visited[r - 1][c]:
dfs(r - 1, c, node)
if r + 1 < rows and not visited[r + 1][c]:
dfs(r + 1, c, node)
if c > 0 and not visited[r][c - 1]:
dfs(r, c - 1, node)
if c + 1 < cols and not visited[r][c + 1]:
dfs(r, c + 1, node)
visited[r][c] = False
# Remove exhausted branches so later searches skip them.
if not node:
parent.pop(ch, None)
for r in range(rows):
for c in range(cols):
dfs(r, c, root)
return found