Straight-Line Word Search in a Character Grid

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a rectangular grid of uppercase letters board (where board[r][c] is the character at row r, column c) and a target string word, implement word_exists(board, word) to check whether word can be read along a single straight-line ray inside the grid.

A valid match selects one starting cell (start_row, start_col) and one fixed compass step (dr, dc) from the eight nonzero directions—horizontal, vertical, or diagonal (dr, dc in {-1, 0, 1} with (dr, dc) != (0, 0))—such that for every index k from 0 to len(word) - 1: - (start_row + k * dr, start_col + k * dc) lies strictly inside the grid bounds, and - board[start_row + k * dr][start_col + k * dc] == word[k].

Paths may not bend mid-word, skip cells, wrap across grid borders, or reuse a cell by standing still. A single-character word matches whenever at least one cell in board holds that character.

Examples

Example 1

Input: board = ["MNP", "QRS", "TUV"], word = "MRV"
Output: True

Starting at (0, 0) ('M') and stepping down-right (+1, +1) visits (0, 0) = 'M', (1, 1) = 'R', and (2, 2) = 'V'.

Example 2

Input: board = ["MNP", "QRS", "TUV"], word = "MNR"
Output: False

Moving from 'M' at (0, 0) to 'N' at (0, 1) locks in the rightward step (0, +1), whose next cell is 'P' at (0, 2) rather than 'R' at (1, 1). Changing direction mid-word is not allowed.

Example 3

Input: board = ["ZZZZ", "TRAM", "ZZZZ"], word = "MART"
Output: True

Starting at (1, 3) ('M') and stepping left (0, -1) reads "MART" backward across row 1.

Example 4

Input: board = ["WXYZ", "JKLM", "NOPQ"], word = "NKY"
Output: True

Starting at (2, 0) ('N') and stepping up-right (-1, +1) visits (2, 0) = 'N', (1, 1) = 'K', and (0, 2) = 'Y'.

Constraints

  • 1 <= len(board) <= 100
  • 1 <= len(board[0]) <= 100, and every row string in board has the same length.
  • 1 <= len(word) <= 100
  • Every character in board and word is an uppercase ASCII letter ('A'–'Z').

Step-by-step walkthrough

  1. Understand the straight-line rule vs snaking word search

    Given a rectangular grid of uppercase letters board (board[r][c] is row r, column c) and a target word, we want to know whether word can be read along one fixed straight line in any of the eight compass directions (horizontal, vertical, or diagonal, forwards or backwards).

    Unlike "snaking" grid puzzles where you may turn at every letter, here choosing a start cell and a direction locks in the entire path:

    Board:
      col 0 1 2
    row 0 M N P
    row 1 Q R S
    row 2 T U V
    
    "MRV": Valid! Start at (0,0) and keep stepping (+1, +1) -> (0,0)='M', (1,1)='R', (2,2)='V'.
    "MNR": Invalid! (0,0)='M' -> (0,1)='N' goes right (0, +1), then (1,1)='R' bends down (+1, 0).
    

    Because every allowed direction moves by at least one row or one column per step, a straight line never visits the same cell twice—so no cell is ever reused as long as we exclude the zero step (0, 0).

  2. Why checking every straight ray is fast enough

    Let R be the number of rows, C be the number of columns, and L be len(word). The constraints say R <= 100, C <= 100, and L <= 100:

    • At most R * C = 10,000 starting cells.
    • 8 possible directions from each starting cell.
    • At most L <= 100 character comparisons along each ray (and most fail on the very first letter or fail the boundary check immediately).

    Even the loose upper bound 10,000 * 8 * 100 = 8,000,000 character checks finishes in milliseconds, and in reality far fewer rays fit inside the board. That means a clean, direct search with O(1) extra memory is the ideal solution—our focus is getting the direction and boundary logic 100% bug-free.

  3. Represent the eight compass directions as `(dr, dc)` steps

    A direction vector (dr, dc) records how much the row index and column index change on each one-letter step: dr = -1 moves up one row, dr = +1 moves down one row, dc = -1 moves left one column, and dc = +1 moves right one column:

       (-1, -1)   (-1,  0)   (-1, +1)
             \       |       /
              \      |      /
       ( 0, -1) -- (r, c) -- ( 0, +1)
              /      |      \
             /       |       \
       (+1, -1)   (+1,  0)   (+1, +1)
    

    Once we pick (start_row, start_col) and (dr, dc), character step of word (for step = 0, 1, ..., L - 1) must sit at:

    cur_row = start_row + step * dr
    cur_col = start_col + step * dc
    
    # Eight nonzero (row_step, col_step) compass directions:
    # up-left, up, up-right, left, right, down-left, down, down-right.
    DIRECTIONS: List[Tuple[int, int]] = [
        (-1, -1), (-1, 0), (-1, 1),
        (0, -1),           (0, 1),
        (1, -1),  (1, 0),  (1, 1),
    ]
    
  4. Check boundaries once at the far endpoint

    Before reading characters along a ray, how do we know the ray never steps off the grid?

    Because (start_row, start_col) is already inside the grid and each coordinate changes at a constant rate (+dr and +dc per step), every cell along the segment lies between the start cell (step = 0) and the final cell (step = L - 1). So if the final cell (end_row, end_col) is inside [0, R - 1] by [0, C - 1], every cell in between is guaranteed to be inside too!

    Why must we check 0 <= end_row and 0 <= end_col explicitly instead of catching Python's IndexError? Because in Python, negative indices wrap around (board[-1] silently reads the bottom row instead of raising an error!), which would falsely wrap paths across opposite edges of the board.

  5. Match characters along a fixed ray

    Now we can write matches_from to test a single (start_row, start_col, dr, dc) ray, and word_exists to try all 8 rays from every cell holding word[0]:

    def matches_from(
        board: List[str],
        word: str,
        start_row: int,
        start_col: int,
        dr: int,
        dc: int,
    ) -> bool:
        """Return True if `word` appears starting at (start_row, start_col) along (dr, dc)."""
        rows = len(board)
        cols = len(board[0])
        word_len = len(word)
    
        # Because (start_row, start_col) is already inside the board and coordinates move
        # in fixed steps, checking the final cell guarantees every intermediate cell fits.
        # Explicit < 0 checks are mandatory because Python's board[-1] wraps to the end!
        end_row = start_row + (word_len - 1) * dr
        end_col = start_col + (word_len - 1) * dc
        if not (0 <= end_row < rows and 0 <= end_col < cols):
            return False
    
        # Walk straight along (dr, dc) without ever changing direction.
        for step in range(word_len):
            cur_row = start_row + step * dr
            cur_col = start_col + step * dc
            if board[cur_row][cur_col] != word[step]:
                return False
    
        return True
    
    
    def word_exists(board: List[str], word: str) -> bool:
        """Return True if `word` appears along any single straight-line direction in `board`."""
        rows = len(board)
        cols = len(board[0])
    
        # Scan every cell as a candidate starting letter, then test all 8 straight rays.
        for start_row in range(rows):
            for start_col in range(cols):
                # Skip cells that do not even match the first character of `word`.
                if board[start_row][start_col] != word[0]:
                    continue
    
                for dr, dc in DIRECTIONS:
                    if matches_from(board, word, start_row, start_col, dr, dc):
                        return True
    
        return False
    

    Check how cleanly a 1-letter word (word_len = 1) works without any special case: end_row = start_row + 0 * dr = start_row and end_col = start_col, which is in bounds, and step = 0 confirms board[start_row][start_col] == word[0].

  6. Walk through Examples 1 and 2

    On board = ["MNP", "QRS", "TUV"], only (0, 0) holds 'M', so both "MRV" and "MNR" only test rays starting at (0, 0) with word_len = 3:

    Direction   (end_row, end_col)   In 3x3 bounds?   Letters read   "MRV"?   "MNR"?
    ---------   ------------------   --------------   ------------   ------   ------
    (-1, -1)    (-2, -2)             No (skip)        -              -        -
    (-1,  0)    (-2,  0)             No (skip)        -              -        -
    (-1, +1)    (-2, +2)             No (skip)        -              -        -
    ( 0, -1)    ( 0, -2)             No (skip)        -              -        -
    ( 0, +1)    ( 0,  2)             Yes              "MNP"          No       No ('P' != 'R')
    (+1, -1)    ( 2, -2)             No (skip)        -              -        -
    (+1,  0)    ( 2,  0)             Yes              "MQT"          No       No ('Q' != 'N')
    (+1, +1)    ( 2,  2)             Yes              "MRV"          Yes!     No ('R' != 'N')
    

    "MRV" returns True on (+1, +1), while "MNR" exhausts all 8 rays and returns False.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Eight nonzero (row_step, col_step) compass directions:
    # up-left, up, up-right, left, right, down-left, down, down-right.
    DIRECTIONS: List[Tuple[int, int]] = [
        (-1, -1), (-1, 0), (-1, 1),
        (0, -1),           (0, 1),
        (1, -1),  (1, 0),  (1, 1),
    ]
    
    
    def matches_from(
        board: List[str],
        word: str,
        start_row: int,
        start_col: int,
        dr: int,
        dc: int,
    ) -> bool:
        """Return True if `word` appears starting at (start_row, start_col) along (dr, dc)."""
        rows = len(board)
        cols = len(board[0])
        word_len = len(word)
    
        # Because (start_row, start_col) is already inside the board and coordinates move
        # in fixed steps, checking the final cell guarantees every intermediate cell fits.
        # Explicit < 0 checks are mandatory because Python's board[-1] wraps to the end!
        end_row = start_row + (word_len - 1) * dr
        end_col = start_col + (word_len - 1) * dc
        if not (0 <= end_row < rows and 0 <= end_col < cols):
            return False
    
        # Walk straight along (dr, dc) without ever changing direction.
        for step in range(word_len):
            cur_row = start_row + step * dr
            cur_col = start_col + step * dc
            if board[cur_row][cur_col] != word[step]:
                return False
    
        return True
    
    
    def word_exists(board: List[str], word: str) -> bool:
        """Return True if `word` appears along any single straight-line direction in `board`."""
        rows = len(board)
        cols = len(board[0])
    
        # Scan every cell as a candidate starting letter, then test all 8 straight rays.
        for start_row in range(rows):
            for start_col in range(cols):
                # Skip cells that do not even match the first character of `word`.
                if board[start_row][start_col] != word[0]:
                    continue
    
                for dr, dc in DIRECTIONS:
                    if matches_from(board, word, start_row, start_col, dr, dc):
                        return True
    
        return False
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture solving a classic newspaper word-search puzzle by placing a laser pointer on a starting letter and aiming it along one of the eight compass directions (up, down, left, right, or any of the four diagonals). Once you aim the laser, the beam travels in a dead-straight line—it cannot bend around corners, skip squares, or wrap off one edge onto the opposite side. Mathematically, we represent the beam's heading as a direction vector (dr, dc)—a pair of integers in {-1, 0, 1} (excluding (0, 0)) telling us how much the row and column change on each step.

Why does a standard recursive grid search fail here? Many candidates instinctively write backtracking (a recursive depth-first search that tries all unused neighbors again at every letter while tracking a visited set). That solves the wrong problem—it allows paths that turn corners (falsely accepting "MNR" in Example 2)—and explores exponentially many branching paths (O(8 * 7^(L - 2))) when a straight line has zero branching once (dr, dc) is chosen (O(L) steps).

Let's trace board = ["MNP", "QRS", "TUV"] (3 rows by 3 columns): - Searching "MRV" (L = 3): only (0, 0) holds 'M'. Trying direction (+1, +1), the far end (0 + 2*1, 0 + 2*1) = (2, 2) is inside the 3x3 grid, and cells (0, 0)='M', (1, 1)='R', (2, 2)='V' all match, returning True. - Searching "MNR" (L = 3): from (0, 0), five directions immediately fail the endpoint check (-2 < 0), while the three in-bounds rays read "MNP" along (0, +1), "MQT" along (+1, 0), and "MRV" along (+1, +1)—none matches "MNR", returning False.

Complexity

Let R be the number of rows, C be the number of columns, and L be the length of word.

  • Time: O(R * C * L). We inspect each of the R * C grid cells once; whenever board[r][c] == word[0], we test 8 constant-direction rays, each doing an O(1) endpoint bounds check followed by at most L character comparisons (8 * R * C * L operations in the worst case, and even fewer because rays whose far endpoint falls outside the grid stop in O(1) before comparing characters).
  • Space: O(1) auxiliary space. We never copy rows, build diagonal strings, allocate a visited set, or use recursion—only a few integer loop variables are stored.

Edge cases

  • Single-letter word (L = 1): word_len - 1 is 0, so (end_row, end_col) equals (start_row, start_col), which is already in bounds, returning True if and only if the letter appears anywhere on the board.
  • Word longer than every grid dimension (L > max(R, C)): Every candidate ray's (end_row, end_col) falls outside [0, R - 1] x [0, C - 1], returning False in O(1) per ray without extra character reads.
  • Non-square grids (1 x C, R x 1, 3 x 4): Bounding end_row against rows and end_col against cols independently handles wide, tall, and 1 x 1 boards cleanly (as in Example 4's 3 x 4 grid).
  • Backwards and diagonal words: Including negative steps like (0, -1) and (-1, +1) naturally finds right-to-left words (such as "MART" in Example 3) and upward diagonals ("NKY" in Example 4) without reversing strings.
  • Palindromes (words like "ABA" that read the same forwards and backwards): Matched cleanly on the first valid endpoint and direction encountered, whereas a single cell ["A"] rejects "AA" because (0, 0) is excluded from DIRECTIONS.

Common mistakes

  • Using backtracking DFS over neighbors at each step: Allows 90-degree and 45-degree turns mid-word (accepting "MNR" on ["MNP", "QRS", "TUV"]) and blows up time complexity on grids filled with repeated letters like 'A'.
  • Relying on try / except IndexError instead of checking < 0: In Python, board[-1] and row[-1] are valid negative indices that read the last row or column, silently wrapping paths across the top and left borders (for example, matching "ABA" on ["AB"]).
  • Including (0, 0) in DIRECTIONS: Generating (dr, dc) with a nested loop over (-1, 0, 1) without skipping (0, 0) stays stationary on one cell and falsely matches "AAA" on a single 'A'.
  • Checking only 4 directions (right, down, down-right, down-left): Misses words written right-to-left ("MART"), bottom-to-top, or up-right ("NKY") unless you also check word[::-1].
  • Swapping or sharing rows and cols bounds: Checking end_col < len(board) instead of len(board[0]) raises IndexError on tall boards and misses valid words on wide boards.

Alternative approaches

  • Extract all full lines + linear string search: Collect all R rows, C columns, R + C - 1 main diagonals, and R + C - 1 anti-diagonals as strings, then check word in line or word[::-1] in line. Pairing this with Knuth-Morris-Pratt (KMP)—a string-matching algorithm that precomputes fallback positions in O(L) so it never re-scans characters—runs in optimal O(R * C + L) time, at the cost of O(R * C) extra space to materialize the line strings (roughly 4 * R * C characters).

Follow-up questions

  • How would you adapt the function to return every matching (start_row, start_col, dr, dc) ray instead of just True or False? Append every (start_row, start_col, dr, dc) tuple where matches_from returns True to a results list instead of returning early. Be sure to clarify two deduplication edge cases with the interviewer: a palindrome like "ABA" matches from both ends along opposite directions (dr, dc) and (-dr, -dc), and a 1-letter word "A" matches all 8 directions from the same cell unless you handle len(word) == 1 once per cell.
  • If you needed to check 10,000 query words against the same 100 x 100 grid, how would you avoid scanning the grid from scratch per word? Insert all query words into a trie (a prefix tree where shared word beginnings share nodes and complete words are marked). Then from each (start_row, start_col) and each of the 8 directions, walk down the trie along the straight ray—stopping immediately as soon as the next grid character has no matching trie child—which finds all matches in O(sum_of_word_lengths + 8 * R * C * max_word_len) time rather than multiplying grid work by the number of queries (or run an Aho-Corasick automaton, a multi-pattern state machine, across each extracted row, column, and diagonal in O(sum_of_word_lengths + R * C + matches) time).
  • How would the algorithm and its worst-case runtime change if paths could change direction at each step without visiting any cell twice? You would switch to recursive backtracking DFS with a visited set (or temporarily marking board[r][c] = '#' in place): at index k, try all 8 adjacent in-bounds unvisited cells matching word[k], and unmark when backtracking. Because worst-case time becomes exponential (O(R * C * 8 * 7^(L - 2))), early pruning—such as verifying letter frequency counts in board cover word and reversing word when word[-1] is rarer on the grid than word[0]—makes a major practical difference.

Follow-up questions

Similar questions

More Reddit interview questions

All 36 Reddit questions →