Word Path Search on a Grid

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a rectangular 2D character array board with rows rows and cols columns, along with a target string word. Each entry board[r][c] holds a single character.

Implement exists(board, word) -> bool to decide whether word can be traced along a sequence of orthogonally neighboring grid squares:

  • Every step between consecutive letters of word must move up, down, left, or right by one square (diagonal moves are disallowed).
  • Within a single candidate path, each (row, col) cell may be visited at most once.
  • Character matching is case-sensitive ("a" and "A" are distinct).
  • When exists finishes, board must retain its exact original contents (any temporary in-place edits made during exploration must be undone before returning).
  • An empty target (word == "") requires zero cells and always evaluates to True, whereas a non-empty word on an empty grid ([] or [[]]) evaluates to False.

Examples

Example 1

Input:
  board = [
    ["T", "U", "N", "K"],
    ["R", "O", "N", "P"],
    ["M", "L", "E", "P"]
  ]
  word = "TUNNEL"

Output: True

Explanation: Starting at (0, 0) = "T", moving right to (0, 1) = "U", right to (0, 2) = "N", down to (1, 2) = "N", down to (2, 2) = "E", and left to (2, 1) = "L" spells "TUNNEL" using six distinct orthogonally connected cells.

Example 2

Input:
  board = [
    ["T", "U", "N", "K"],
    ["R", "O", "N", "P"],
    ["M", "L", "E", "P"]
  ]
  word = "NONE"

Output: False

Explanation: Although the grid contains two "N"s, one "O", and one "E", no legal path spells "NONE". Starting at (0, 2) = "N" has no adjacent "O". Starting at (1, 2) = "N" and stepping left to (1, 1) = "O" gets stuck: stepping right back onto (1, 2) would reuse an already visited square, and the other "N" at (0, 2) sits diagonally from (1, 1).

Example 3

Input:
  board = [
    ["c", "c"],
    ["t", "z"]
  ]
  word = "cct"

Output: True

Explanation: Trying (0, 0) -> (0, 1) reaches a dead end because (1, 1) holds "z". Backtracking and starting instead at (0, 1) = "c", moving left to (0, 0) = "c", and moving down to (1, 0) = "t" spells "cct".

Constraints

  • 0 <= len(board) <= 12
  • 0 <= len(board[r]) <= 12, and all rows have identical length
  • Every cell board[r][c] is a 1-character string (letters, digits, or symbols; comparisons are case-sensitive)
  • 0 <= len(word) <= 150
  • board must remain unmodified after exists(board, word) returns

Step-by-step walkthrough

  1. Understand the rules and boundary cases

    We are given a rectangular rows x cols grid board of single-character strings and a target string word. We want exists(board, word) to return True if we can spell word by walking from square to square under three rules:

    • Orthogonal moves only: each step moves up, down, left, or right (diagonals are not allowed).
    • No cell reuse within a path: a single path cannot step onto the same (row, col) square twice, though two separate path attempts may try the same square.
    • Exact, non-destructive check: comparisons are case-sensitive ("a" != "A"), and even if we temporarily edit board during the search, board must look identical when exists returns.
    Board:             Valid path for "pqsr":      Invalid for "ps" (diagonal)
      p  q             (0,0) -> (0,1) -> (1,1)     Invalid for "pqp" (reuses (0,0))
      r  s                   -> (1,0)
    

    Before writing the search, lock down the boundary cases: - If word == "", zero letters are needed, so the empty path immediately succeeds (True). - Otherwise, if board has zero rows ([]) or zero columns ([[]]), no letters exist, so return False.

  2. Why enumerating every path first is wasteful

    A naive brute-force plan generates every non-overlapping path of length L = len(word) on the grid and checks whether any path's letters equal word. How fast does the number of paths grow?

    A word of L letters visits L cells joined by L - 1 steps: - Step 1 from the starting cell can move in at most 4 directions. - Each of the remaining L - 2 steps can move in at most 3 new directions, because stepping straight back onto the previous cell is forbidden.

    That means up to 4 * 3^(L - 2) paths per starting cell (for L >= 2). Generating all of them when the very first cell does not even match word[0] wastes almost all of the work.

    Instead, we use backtracking — a search strategy that builds a candidate path one step at a time and abandons ("backs out of") a branch the instant a letter fails to match. Most wrong branches die on the first or second character instead of growing to length L.

  3. Frame one recursive question per cell

    We can express the whole search with a single helper function, _match_from(board, word, index, row, col), which answers one focused question:

    Can the remaining suffix word[index:] be spelled starting at (row, col) without stepping onto any cell already used earlier in the current path?

    Let's check what happens at (row, col) in order: 1. Out of bounds: if row < 0, row >= len(board), col < 0, or col >= len(board[0]), we stepped off the grid, so return False. (In Python, we must check < 0 explicitly because board[-1] silently wraps around to the last row!) 2. Letter mismatch: if board[row][col] != word[index], this cell cannot supply the next letter, so return False. 3. Finished the word: if index == len(word) - 1, we just matched the final character of word, so return True! 4. Recurse to neighbors: mark (row, col) as used on the current path, try matching index + 1 at each of the 4 orthogonal neighbors (DIRECTIONS), unmark (row, col), and return whether any neighbor succeeded.

  4. Mark visited cells in place and always restore them

    Normally, depth-first search (DFS, exploring as deep as possible along one branch before backing up) tracks the active path in a separate rows x cols boolean visited grid. We can avoid that O(rows * cols) matrix by marking the board in place:

    • What sentinel value is safe? Every word[index] is a 1-character string (len == 1). If we temporarily overwrite board[row][col] with the empty string VISITED = "" (len == 0), then board[row][col] != word[index] is guaranteed to be True for any character word might contain (even #, digits, or punctuation!). So our existing mismatch check automatically rejects cells already on the current path.
    • Why use a found flag instead of returning inside the loop? If a neighbor returns True and we returned True immediately, board[row][col] would stay overwritten with "" in the caller's grid! Saving found = True, breaking out of the neighbor loop, and running board[row][col] = saved_letter right before return found guarantees a single exit path that cleans up after both hits and dead ends.
    from typing import List
    
    # Sentinel written into a board cell while it sits on the active DFS path.
    # Because every character word[index] has length 1 and VISITED has length 0,
    # a marked cell can never match word[index] (even if word contains "#" or spaces).
    VISITED = ""
    
    # Four orthogonal steps (down, up, right, left) as (row_delta, col_delta) pairs.
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def _match_from(
        board: List[List[str]],
        word: str,
        index: int,
        row: int,
        col: int,
    ) -> bool:
        """Return True if word[index:] can be formed starting at (row, col) without reusing marked cells."""
        # Check bounds strictly (< 0 and >= len) before indexing; negative indices in Python wrap around!
        if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]):
            return False
    
        # Rejects both wrong letters and cells already on the current path (whose value is VISITED == "").
        if board[row][col] != word[index]:
            return False
    
        # Base case: we just matched the final character of word, so a complete valid path exists.
        if index == len(word) - 1:
            return True
    
        # Mark (row, col) in place so recursive steps cannot step back onto this cell.
        saved_letter = board[row][col]
        board[row][col] = VISITED
    
        found = False
        for row_delta, col_delta in DIRECTIONS:
            next_row = row + row_delta
            next_col = col + col_delta
            if _match_from(board, word, index + 1, next_row, next_col):
                found = True
                break  # Stop exploring remaining directions as soon as one path succeeds
    
        # Restore the cell BEFORE returning on both success and failure so the caller's board is untouched.
        board[row][col] = saved_letter
        return found
    
  5. Add two fast pre-checks in O(L) extra space

    Backtracking still runs into trouble on adversarial inputs like a board full of "a" and word = "aaaaaaaab": every prefix of "a"s matches, so DFS explores countless paths before discovering there is no "b" anywhere on the board. Two quick linear checks rule out impossible words up front:

    1. Length cap: since no cell can be visited twice, any word with len(word) > rows * cols cannot fit on the board.
    2. Letter-count check: count how many times each character appears in word using remaining = Counter(word). As we scan board, we decrement remaining[letter] ONLY for letters present in remaining. Notice why we count word rather than building a Counter of the entire board: remaining stores at most len(word) keys, preserving our O(L) extra-space guarantee even on huge grids with arbitrary characters!
    from collections import Counter
    from typing import List
    
    
    def _has_enough_letters(board: List[List[str]], word: str) -> bool:
        """Return True if the board has at least as many copies of each letter as word needs."""
        # remaining: Counter mapping each distinct needed letter -> count still needed, e.g. {'A': 1, 'B': 2}.
        # Tracking only letters from word keeps extra memory at O(len(word)) instead of O(rows * cols).
        remaining = Counter(word)
        for row in board:
            for letter in row:
                if letter in remaining:
                    remaining[letter] -= 1
    
        for needed_count in remaining.values():
            if needed_count > 0:
                return False
        return True
    
  6. Trace Sample 1 and Sample 2 step by step

    Let's trace word = "TUNNEL" (L = 6, indices 0..5) on the 3 x 4 board from Example 1:

    Initial board:              Active path at index = 4 ('E' at (2,2)):
      T  U  N  K                  "" "" ""  K
      R  O  N  P                  R  O  ""  P
      M  L  E  P                  M  L  ""  P
    
    • (0,0) matches word[0] = 'T', overwrites (0,0) with "".
      • Down (1,0) = 'R' != 'U' (returns False).
      • Up (-1,0) is out of bounds (returns False).
      • Right (0,1) = 'U' matches word[1], overwrites (0,1) with "".
        • Down (1,1) = 'O' fails; up (-1,1) is out of bounds; right (0,2) = 'N' matches word[2], marks "".
          • Down (1,2) = 'N' matches word[3], marks "".
            • Down (2,2) = 'E' matches word[4], marks "" (shown on the right above).
              • Down (3,2) is out of bounds.
              • Up (1,2) holds "", which fails "" != 'L' — preventing us from stepping backward!
              • Right (2,3) = 'P' != 'L'.
              • Left (2,1) = 'L' matches word[5] (index == 5, the last index) -> returns True!

    As each recursive call breaks out of its loop, it executes board[row][col] = saved_letter, restoring (2,2) -> 'E', (1,2) -> 'N', (0,2) -> 'N', (0,1) -> 'U', and (0,0) -> 'T'.

    Now compare two False queries on the same grid: - For word = "TROT", _has_enough_letters sees remaining['T'] == 2 while the grid holds only one 'T', returning False before starting DFS. - For Example 2 (word = "NONE"), _has_enough_letters passes because the grid holds two 'N's, one 'O', and one 'E'. During DFS, (1,2) = 'N' steps left to (1,1) = 'O', where stepping back right onto (1,2) sees "" != 'N' and (0,2) = 'N' is unreachable diagonally — so (1,1) and (1,2) restore their letters and exists cleanly returns False.

  7. Complete solution

    Put exists, _has_enough_letters, and _match_from together:

    from collections import Counter
    from typing import List
    
    # Sentinel written into a board cell while it sits on the active DFS path.
    # Because every character word[index] has length 1 and VISITED has length 0,
    # a marked cell can never match word[index] (even if word contains "#" or spaces).
    VISITED = ""
    
    # Four orthogonal steps (down, up, right, left) as (row_delta, col_delta) pairs.
    DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))
    
    
    def exists(board: List[List[str]], word: str) -> bool:
        # Phase 1: Handle trivial word and empty-grid boundaries.
        if word == "":
            return True
        if not board or not board[0]:
            return False
    
        rows = len(board)
        cols = len(board[0])
    
        # Phase 2: Fast pruning before launching an exponential search.
        # Since no cell can be visited twice, a path holds at most rows * cols letters.
        if len(word) > rows * cols:
            return False
        if not _has_enough_letters(board, word):
            return False
    
        # Phase 3: Try starting a depth-first path from every cell on the grid.
        for row in range(rows):
            for col in range(cols):
                if _match_from(board, word, 0, row, col):
                    return True
        return False
    
    
    def _has_enough_letters(board: List[List[str]], word: str) -> bool:
        """Return True if the board has at least as many copies of each letter as word needs."""
        # remaining: Counter mapping each distinct needed letter -> count still needed, e.g. {'A': 1, 'B': 2}.
        # Tracking only letters from word keeps extra memory at O(len(word)) instead of O(rows * cols).
        remaining = Counter(word)
        for row in board:
            for letter in row:
                if letter in remaining:
                    remaining[letter] -= 1
    
        for needed_count in remaining.values():
            if needed_count > 0:
                return False
        return True
    
    
    def _match_from(
        board: List[List[str]],
        word: str,
        index: int,
        row: int,
        col: int,
    ) -> bool:
        """Return True if word[index:] can be formed starting at (row, col) without reusing marked cells."""
        # Check bounds strictly (< 0 and >= len) before indexing; negative indices in Python wrap around!
        if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]):
            return False
    
        # Rejects both wrong letters and cells already on the current path (whose value is VISITED == "").
        if board[row][col] != word[index]:
            return False
    
        # Base case: we just matched the final character of word, so a complete valid path exists.
        if index == len(word) - 1:
            return True
    
        # Mark (row, col) in place so recursive steps cannot step back onto this cell.
        saved_letter = board[row][col]
        board[row][col] = VISITED
    
        found = False
        for row_delta, col_delta in DIRECTIONS:
            next_row = row + row_delta
            next_col = col + col_delta
            if _match_from(board, word, index + 1, next_row, next_col):
                found = True
                break  # Stop exploring remaining directions as soon as one path succeeds
    
        # Restore the cell BEFORE returning on both success and failure so the caller's board is untouched.
        board[row][col] = saved_letter
        return found
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine solving a word-search puzzle by placing a penny on each square as your finger traces the word one letter at a time. Whenever you reach a dead end — all adjacent squares are off the board, hold the wrong letter, or already have a penny on them — you lift the last penny and try a different neighbor from the previous square. That step-forward-and-undo pattern is called backtracking (building a candidate solution one choice at a time and undoing a choice as soon as it cannot lead to a valid answer).

The naive alternative is to generate every possible non-overlapping path of length L across the grid first and compare each finished string with word. That fails quickly because the number of simple paths grows exponentially (O(3^L) per start square), wasting huge amounts of work extending paths whose very first or second letter was already wrong. Worse, storing a separate rows x cols boolean visited grid allocates O(rows * cols) memory even when word is only 3 or 4 letters long.

Instead, we run a depth-first search (DFS, following one path as deep as matching letters allow before backing up) directly on board and use the cell itself as the penny: while (row, col) is on the active path, we temporarily overwrite board[row][col] with "", then restore its original letter before returning. Watch how this plays out on Example 3, searching for "cct" on a 2 x 2 grid:

Board:
  (0,0)='c'   (0,1)='c'
  (1,0)='t'   (1,1)='z'
  1. Try start (0,0): matches 'c' (index = 0), marks (0,0) = "". Down (1,0) = 't' fails 'c', so it moves right to (0,1) = 'c' (index = 1), marking (0,1) = "". From (0,1), down (1,1) = 'z' fails 't' and left (0,0) = "" fails 't'. Dead end! Both (0,1) and (0,0) restore 'c'.
  2. Try start (0,1): matches 'c' (index = 0), marks (0,1) = "". Left (0,0) = 'c' matches index = 1, marks (0,0) = "". From (0,0), down (1,0) = 't' matches index = 2 (the last letter!). Both marked cells restore 'c' as the calls unwind, returning True.

Complexity

  • Time: O(R * C * 3^L) in the worst case, where R is the number of rows, C is the number of columns, and L is len(word). First, our length check and letter-frequency scan inspect word (L characters) and board (R * C cells) once in O(R * C + L) time. Then we may start a DFS from each of the R * C grid cells. A path of L cells takes L - 1 steps: for L >= 2, the first step tries at most 4 neighbors, and each of the remaining L - 2 steps can enter at most 3 unvisited neighbors because the cell we just came from is marked "". Summing across levels gives O(3^L) recursive calls per starting cell. (This bound is tight: on a grid of 'a's with two separated 'b's, searching for "a" * 10 + "bb" passes the letter-count check and explores every 10-cell path of 'a's.)
  • Space: O(L) extra memory. Because we mark visited cells in place on board instead of allocating a Visited[R][C] matrix, the recursion call stack holds at most L active frames (one per matched character of word), and _has_enough_letters stores a Counter of only the distinct characters in word (at most L keys), never O(R * C).

Edge cases

  • Empty word (word == ""): returns True immediately (even on an empty board []), because zero cells are needed to spell zero characters.
  • Empty board ([] or [[]] with non-empty word): returns False before touching board[0][0].
  • Single-cell board ([["q"]]): "q" returns True, "p" returns False, and "qq" returns False because (0, 0) cannot be used twice.
  • Word longer than total cells (len(word) > R * C): pruned immediately in O(1) time, e.g., "a" * 10 on a 3 x 3 grid.
  • Full-board snake path ("a" * 9 on a 3 x 3 grid of "a"): returns True via a winding path that visits all 9 cells once.
  • Case sensitivity and special characters: "a" does not match "A", and words containing "#" or spaces still work because VISITED = "" has length 0 whereas every word[index] has length 1.
  • Board preservation: board is guaranteed to equal its original contents whether exists returns True or False.

Common mistakes

  • Returning True before restoring board[row][col]: writing if _match_from(...): return True inside the loop leaves "" scattered across the caller's board whenever a word is found. Always store found = True, break, restore board[row][col] = saved_letter, and only then return.
  • Using a printable character like "#" as the visited marker: if an input test searches for "A#B" on a board containing "#", a marked cell falsely matches '#'! Using "" (empty string) cannot collide with any single character word[index].
  • Forgetting Python's negative-index wraparound: omitting row < 0 or col < 0 lets board[-1][col] read the bottom row of the grid instead of failing out of bounds, allowing illegal wraparound paths across opposite edges.
  • Not removing cells from a visited set when backtracking: if you use a set instead of in-place marking and only call visited.add((r, c)) without visited.remove((r, c)) on backtrack, one failed branch permanently blocks valid paths that pass through (r, c) from a different direction.
  • Counting the whole board into a hash map when O(L) space was requested: building Counter over all R * C board cells can use O(R * C) memory on arbitrary alphabets; counting word (Counter(word)) and decrementing only matching keys keeps space strictly O(L).

Alternative approaches

  • Separate rows x cols boolean visited matrix: same O(R * C * 3^L) time, O(R * C + L) space. Prefer this in multi-threaded servers where board is shared across threads read-only, or when rows are immutable strings (List[str]).
  • Search from the rarer endpoint of word: if word[-1] appears fewer times on board than word[0], reversing word searches the exact same undirected grid paths in reverse while starting from fewer candidate cells and failing earlier on heavily skewed grids (such as "aaaaab").

Follow-up questions

  • How can we track the active path directly inside board without allocating a separate visited array, and what time and space bounds result? Before exploring neighbors of (row, col), save saved_letter = board[row][col] in a local variable on the call stack and set board[row][col] = "". Because every word[index] has length 1, any step back onto (row, col) sees "" != word[index] and returns False immediately; once neighbor calls finish, set board[row][col] = saved_letter to restore the grid. Worst-case time remains O(R * C * 3^L) (4 choices on step 1, at most 3 unvisited choices on the remaining L - 2 steps from each of R * C start cells), while extra space drops from O(R * C + L) to O(L) for the recursion stack and word counter.
  • How would your approach change if we had to search for thousands of target words across the same grid? Insert all target words into a trie (a prefix tree where words sharing a starting prefix share the same path of nodes from the root) and run a single DFS from each board cell that walks the grid and the trie simultaneously. Shared prefixes like "cat", "catch", and "category" are traced once instead of three separate times, and once a word is found you can prune empty leaf branches from the trie so later starts skip them.
  • What changes in both code and worst-case runtime if diagonal neighbor steps are also permitted? Expand DIRECTIONS from 4 offsets to all 8 horizontal, vertical, and diagonal offsets. The first step from a start cell then branches at most 8 ways and every subsequent step branches at most 7 ways (excluding the cell we just came from), increasing worst-case time to O(R * C * 7^L) while keeping extra space at O(L).
  • How can you prevent stack-overflow errors in Python when the grid and target word contain thousands of characters? Replace recursion with an explicit stack of state frames [row, col, index, next_dir_idx]. Pushing a frame saves and marks board[row][col] = ""; each iteration advances next_dir_idx (0..3) to push the next matching neighbor, and when next_dir_idx == 4 (or when cleaning up after finding the end of word), popping a frame restores board[row][col] in O(L) heap memory without touching Python's ~1,000-frame call-stack cap.

Follow-up questions

Similar questions

More Turo interview questions

All 6 Turo questions →