Skip to content
mlmentorship

Own visited cells only for the current word path

Trace a board path, restore cells after success or failure, then support arbitrary characters or count every coordinate path.

Published · 16 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A rectangular board of independent mutable single-character rows and a string word. Output. Return True if some allowed path spells the complete word; otherwise return False. Rules. Consecutive characters must use up, down, left, or right neighbors, never diagonal neighbors. A path cannot reuse a coordinate; different candidates may reuse cells. Exclude # from board and word. The reference restores the board on normal return. An empty word succeeds even on an empty board; a nonempty word fails on an empty board. Example. Rows "ABCE", "SFCS", "ADEE" contain a path spelling "ABCCED", so return True. The same board returns False for "ABCB" because the only candidate would need to reuse its B cell.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

A recursive path owns its marked cells; failed directions return false, and every accepted cell is restored before that call returns.

Problem trace

A cell is unavailable only within the current search path

Input and goalCheck whether a word can be formed by neighboring board cells without reusing a cell.
Start the outer scanStart ABCCED at A in cell (0,0); each active call owns one marked coordinate.
Astart ABCESFCSADEE
wordABCCEDcallsearch(0, 0, 0)checkboard[0][0] = A = word[0]
start A
(0, 0)
word
ABCCED
call
search(0, 0, 0)

Recognize it
A word must be assembled as one neighboring-cell path, choices branch in four directions, and a cell may be used once per candidate path but may be reused by later candidates.
Keep true
At search(row, col, index), every # cell is exactly one character of the current prefix word[0:index]. Before returning, the call restores its own cell, so sibling branches and later starts see the original board.
Reuse it
For path-constrained search, choose one option, mark only the state owned by that choice, recurse, then undo before returning. The same choose-explore-unchoose discipline applies to mazes, permutations, and constraint search.
Start ABCCED at A in cell (0,0); each active call owns one marked coordinate. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can a cell be unavailable inside the current path yet available again to a later independent search?
Full interview answer 16 min read

Determine whether a word can be spelled along a nonrepeating orthogonal path through a letter board.

Problem

Input. A rectangular board of independent mutable single-character rows and a string word.

Output. Return True if some allowed path spells the complete word; otherwise return False.

Rules. Consecutive characters must use up, down, left, or right neighbors, never diagonal neighbors. A path cannot reuse a coordinate; different candidates may reuse cells. Exclude # from board and word. The reference restores the board on normal return. An empty word succeeds even on an empty board; a nonempty word fails on an empty board.

Example. Rows "ABCE", "SFCS", "ADEE" contain a path spelling "ABCCED", so return True. The same board returns False for "ABCB" because the only candidate would need to reuse its B cell.

Picture

At search(row, col, index), marked ancestors spell word[:index]. The candidate must be in bounds, unused and equal to the next character. Save its character, mark it, then try down, up, right and left.

The trace follows (0,0),(0,1),(0,2),(1,2),(2,2),(2,1). At E, down is outside, up is already marked and right contains the wrong character. Left reaches D and completes the word. Completion is checked before reading another cell; no additional valid neighbor is required.

The Boolean result short-circuits remaining directions, but each accepted call still restores its own cell. Restoration unwinds D,E,C,C,B,A. Path ownership is temporary, unlike the permanent component marking used for island counting.

Problem trace

Separate two-cell ABA request: the third visit reuses an already-owned cell

Worked example: a matching letter cannot reuse a cell already on this pathOn a two-cell board A,B, target ABA would require cell 0 twice. The final A matches in value but is unavailable on the active path.The final A matches in value but asksfor an already-used cellBoard: only two adjacent cells existAcell 0Bcell 1Requested visits for ABAAcell 0Bcell 1Acell 0Cell zero is already on this path.The third request is refused.
Read it this way: On a two-cell board A,B, target ABA would require cell 0 twice. The final A matches in value but is unavailable on the active path. Does the final matching A create a third board cell, or request the already-used first cell again?
Reference drawing

Problem trace

A cell is unavailable only within the current search path

Worked example: a matching letter cannot reuse a cell already on this pathOn a two-cell board A,B, target ABA would require cell 0 twice. The final A matches in value but is unavailable on the active path.The final A matches in value but asksfor an already-used cellBoard: only two adjacent cells existAcell 0Bcell 1Requested visits for ABAAcell 0Bcell 1Acell 0Cell zero is already on this path.The third request is refused.
Execution trace
Input and goalCheck whether a word can be formed by neighboring board cells without reusing a cell.
Start the outer scanStart ABCCED at A in cell (0,0); each active call owns one marked coordinate.
Astart ABCESFCSADEE
wordABCCEDcallsearch(0, 0, 0)checkboard[0][0] = A = word[0]
start A
(0, 0)
word
ABCCED
call
search(0, 0, 0)

Recognize it
A word must be assembled as one neighboring-cell path, choices branch in four directions, and a cell may be used once per candidate path but may be reused by later candidates.
Keep true
At search(row, col, index), every # cell is exactly one character of the current prefix word[0:index]. Before returning, the call restores its own cell, so sibling branches and later starts see the original board.
Reuse it
For path-constrained search, choose one option, mark only the state owned by that choice, recurse, then undo before returning. The same choose-explore-unchoose discipline applies to mazes, permutations, and constraint search.
Start ABCCED at A in cell (0,0); each active call owns one marked coordinate. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can a cell be unavailable inside the current path yet available again to a later independent search?
Read it this way: On a two-cell board A,B, target ABA would require cell 0 twice. The final A matches in value but is unavailable on the active path. Does the final matching A create a third board cell, or request the already-used first cell again?

Code

def word_search(board: list[list[str]], word: str) -> bool:
   if not word:
      return True
   if not board or not board[0]:
      return False

   def search(row: int, col: int, index: int) -> bool:
      if index == len(word):
         return True
      if not (0 <= row < len(board) and 0 <= col < len(board[0])):
         return False
      if board[row][col] != word[index]:
         return False

      char = board[row][col]
      board[row][col] = "#"
      found = (
         search(row + 1, col, index + 1)
         or search(row - 1, col, index + 1)
         or search(row, col + 1, index + 1)
         or search(row, col - 1, index + 1)
      )
      board[row][col] = char
      return found

   return any(
      search(row, col, 0)
      for row in range(len(board))
      for col in range(len(board[0]))
   )

For word length , a loose upper bound is time and path stack space. The search is exponential, not linear merely because each current path avoids repeats. Long words can exceed Python’s recursion limit. Normal returns restore the board; an exception can leave this in-place reference marked.

Failure Check

On board AB, ABA must fail because the first A cannot be reused. A permanent visited set also incorrectly blocks coordinates needed by later candidates. Returning immediately on success before restoring would change the caller’s board.

Change to an Arbitrary Alphabet

New task: Allow # in the board or query.

Picture and change: Track used coordinates in a path-local set instead of overwriting characters. The finally block releases ownership even when a recursive call raises.

def word_search_set(board, word):
   if not word:
      return True
   if not board or not board[0]:
      return False
   used = set()
   def search(row, col, index):
      if index == len(word):
         return True
      if not (0 <= row < len(board) and 0 <= col < len(board[0])) or (row, col) in used or board[row][col] != word[index]:
         return False
      used.add((row, col))
      try:
         return any(search(row + row_step, col + col_step, index + 1) for row_step, col_step in ((1,0),(-1,0),(0,1),(0,-1)))
      finally:
         used.remove((row, col))
   return any(search(row, col, 0) for row in range(len(board)) for col in range(len(board[0])))

Check: Board [["A","B"]] and "AB#" return False; board [["#","A"]] and "#A" return True. The first case fools the sentinel reference into accepting a previously used cell as a literal #. This version never modifies the board.

Use when: No character can be reserved as a marker.

Change to Counting Coordinate Paths

New task: Count every matching simple coordinate path, including opposite traversal orders.

Picture and change: Sum branches instead of stopping at one, and emit one count at the final matched cell.

def count_word_paths(board, word):
   if not word:
      return 1
   if not board or not board[0]:
      return 0
   used = set()
   def search(row, col, index):
      if not (0 <= row < len(board) and 0 <= col < len(board[0])) or (row, col) in used or board[row][col] != word[index]:
         return 0
      if index == len(word) - 1:
         return 1
      used.add((row, col))
      total = sum(search(row + row_step, col + col_step, index + 1) for row_step, col_step in ((1,0),(-1,0),(0,1),(0,-1)))
      used.remove((row, col))
      return total
   return sum(search(row, col, 0) for row in range(len(board)) for col in range(len(board[0])))

Check: A two-by-two board of A has eight directed paths spelling AA: four starts, each with two neighbors. The empty word contributes one empty path, including on an empty board. Counting retains exponential worst-case search and current-path storage, not storage for all returned witnesses.

Use when: Distinct coordinate paths, rather than distinct strings, define the output.

Transfer Check

Why not sum the original four recursive calls after reaching the final character?

Answer

All four would report the same completed path, multiplying its contribution by four. Emit once at the final matched cell instead.