KatInterview

Trace a Target String Through a Character Grid

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbacktrackingdepth-first-searchgrid

Last 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.