Trace a Target String Through a Character Grid
Trees & GraphsModel answerLast updated
Decide whether a word can be spelled by a non-repeating, four-directional path of adjacent cells in a character matrix, with pruning and complexity analysis.
You are handed a rectangular matrix of single characters and a target string word. Cells are connected to their four orthogonal neighbors (up, down, left, right); diagonals do not count.
Determine whether word can be spelled by walking a path through the matrix such that:
- the characters along the path, in order, equal
word; - each step moves to an orthogonally adjacent cell;
- no cell is visited more than once within a single path.
Return a boolean. You are expected to state the algorithm, justify correctness, give time and space bounds in terms of the number of cells N and the word length L, and describe pruning tricks that make the search practical. Then write working code.
Clarify these boundaries up front rather than guessing:
- Matching is exact/case-sensitive.
- The empty string is trivially present →
True. - An empty (or zero-column) matrix cannot contain a non-empty word →
False. - Only a yes/no answer is required, not the path itself.
- Say whether mutating the input matrix is acceptable; if not, plan for a separate visited structure.
Hints
Hint 1
Every cell is a candidate start. From a start, try to match word[k] at the current cell, then recurse into the four neighbors for k+1 — but only after marking the cell so the path can't loop back onto itself.
Hint 2
The mark must be undone when a branch fails. A visited flag that is never cleared rejects perfectly valid paths; think of the marker as 'used on the current path', not 'used forever'.
Hint 3
Before searching at all, compare character histograms of matrix and word, and consider searching the reversed word when the word's first character is the more common one on the board — the path can be walked either direction.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the approach
The search space is the set of simple (non-self-intersecting) paths whose characters spell the prefix of word. A depth-first search with explicit undo — classic backtracking — enumerates exactly that set, starting a fresh search from each cell.
Define dfs(r, c, k) = "can word[k:] be matched starting at cell (r, c), given the cells already consumed by the current path?" The recurrence:
- If
(r, c)is out of bounds, fail. - If the cell's character is not
word[k], fail. (If you mark used cells with a sentinel character, this test also rejects revisits for free.) - If
k == L - 1, the last character matched — succeed. - Otherwise mark
(r, c)used, recurse into the four neighbors withk + 1, then unmark and return whether any neighbor succeeded. Short-circuit withorso the first success stops the search.
The outer loop tries every cell as a start, skipping cells that don't match word[0].
Why the mark/unmark discipline is the crux
A cell that dead-ends on one branch may be essential on another. The invariant that makes the algorithm correct is: at all times, the set of marked cells equals exactly the prefix of the current path. Marking on entry and restoring on exit maintains that invariant, so:
- Soundness: any accepted path matched every character and never reused a cell, so the answer
Trueis justified. - Completeness: from every start we try every adjacent unused cell at every depth, so every valid simple path with a matching prefix is explored. No valid path is blocked by stale state.
A frequent bug is a global visited structure that is set but never reset — this silently returns False on valid inputs. Note also that the restore must happen on the success path too, otherwise the board is left corrupted (matters if the function is called again, or if the interviewer inspects the matrix).
Complexity
Let N = rows × cols, L = len(word).
- Time:
O(N · 3^(L-1)), often writtenO(N · 3^L). The start cell is fixed, so the first hop has at most 4 options; every subsequent hop has at most 3, because the immediately previous cell is on the current path and therefore blocked. Branching is multiplicative, so a start explores at most4 · 3^(L-1)partial paths. Character mismatches prune most of them long before reaching depthLin practice, but the bound is the worst case. - Space:
O(L)recursion depth if you mark in place. A separate boolean visited matrix addsO(N).
Pruning that interviewers expect
- Length gate.
L > N→Falseimmediately. - Histogram gate. Count characters in the matrix once. If the word needs more copies of any character than exist, return
False. This isO(N + L)and eliminates many impossible inputs before any exponential work. Update counts incrementally if you prefer, but a single pre-check is simplest. - Search the cheaper direction. A path readable forward is readable backward, so a word exists iff its reverse does. If
count(word[0]) > count(word[-1])on the board, reverse the word — fewer candidate starting cells. On adversarial inputs (a board of'A's targeting"AAAAAAB"), searching the reversed string starts only at the rareBinstead of everyA. - Early exit via short-circuit
or, plus theword[0]filter in the outer loop.
Practical limits
Python's default recursion limit (~1000) will overflow on very long words; mention an explicit stack of (r, c, k, direction_index) frames that restores a cell when its direction list is exhausted, or bump the recursion limit if allowed. If the interviewer disallows mutating the input, swap the sentinel for a boolean grid — same algorithm, O(N) extra space. If the follow-up is "find all words from a dictionary that appear in the grid," build a trie and run one DFS per cell that advances through trie nodes, pruning subtrees as words are completed — this replaces per-word repeated scanning.
Reference implementation
from collections import Counter
def word_in_grid(board, word):
if not word:
return True
if not board or not board[0]:
return False
rows, cols = len(board), len(board[0])
if len(word) > rows * cols:
return False
need = Counter(word)
have = Counter(ch for row in board for ch in row)
if any(have[ch] < n for ch, n in need.items()):
return False
if have[word[0]] > have[word[-1]]:
word = word[::-1] # search the more constrained direction
last = len(word) - 1
def dfs(r, c, k):
if not (0 <= r < rows and 0 <= c < cols):
return False
if board[r][c] != word[k]: # mismatched or marked '#'
return False
if k == last:
return True
saved = board[r][c]
board[r][c] = "#"
found = (dfs(r+1, c, k+1) or dfs(r-1, c, k+1)
or dfs(r, c+1, k+1) or dfs(r, c-1, k+1))
board[r][c] = saved # undo on both success and failure
return found
for r in range(rows):
for c in range(cols):
if board[r][c] == word[0] and dfs(r, c, 0):
return True
return False
The sentinel '#' assumes the alphabet excludes it; if not, use a boolean grid.
Edge cases to walk through aloud
word == ""→True; empty board with non-empty word →False.[["a"]]with"a"→True; with"aa"→False(cell can't be reused).- A pattern like
"ABCB"over a board containingA B C Emust fail — it would require revisitingB, which the backtracking correctly rejects. - Repeated-character boards that blow up branching — exactly where the histogram and reversal pruning pay off.
What strong candidates demonstrate
A crisp recurrence, the mark/restore invariant stated explicitly, the 3^L bound with the reason for 3 rather than 4, proactive O(N) pre-checks, awareness of recursion depth and input mutation, and a clean generalization path (trie) when the interviewer pushes to multiple words. The most common mistakes are forgetting to unmark, using 1 in the complexity as if all four hops branch, and scanning only the first character without handling revisits.