Straight-Line Word Search Across Eight Directions
Arrays & HashingAuto-graded · 24 test casesLast updated
Tests whether a target word appears in a letter grid along any single unbroken ray, locking direction after the first letter.
Straight-Line Word Search Across Eight Directions
You are given a rectangular grid of uppercase letters and a target word. Decide whether the word can be read from some starting cell by moving one step at a time in a single fixed direction — the same direction for every letter, from the first to the last.
Movement Rules
Pick any starting cell and any one of the eight compass directions (left, right, up, down, or any of the four diagonals). Every subsequent letter must come from the next cell in exactly that direction. You may not:
- change direction after the first step,
- skip or revisit cells,
- wrap around from one edge of the grid to the opposite edge.
The entire path must stay inside the grid.
Task
Implement find_word_in_grid(board, word) that returns True if the word appears as a straight-line sequence anywhere in the grid, and False otherwise.
Constraints
1 <= len(board) <= 100(number of rows)1 <= len(board[0]) <= 100(number of columns; all rows have the same length)- Every cell contains an uppercase ASCII letter (
A–Z) 1 <= len(word) <= 100- Every character in
wordis an uppercase ASCII letter - A one-letter word is present whenever any cell holds that letter
- A word longer than the grid can accommodate in any direction returns
False
Examples
Example 1
Input: find_word_in_grid(['ABC', 'DEF', 'GHI'], 'AEI')
Output: True
Example 2
Input: find_word_in_grid(['ABC', 'DEF', 'GHI'], 'ABE')
Output: False
Example 3
Input: find_word_in_grid(['HELLO', 'XXXXX', 'XXXXX'], 'OLLEH')
Output: True
Example 4
Input: find_word_in_grid(['ABCD', 'EFGH', 'IJKL', 'MNOP'], 'AFKP')
Output: True
Hints
Hint 1
A valid placement is completely determined by three things: a starting cell, a direction, and the word itself. Once those are fixed, the position of every letter is known — there is no branching or backtracking involved.
Hint 2
For a path of length L starting at (r, c) with step (dr, dc), the final cell lands at (r + dr*(L-1), c + dc*(L-1)). Because each coordinate changes monotonically along the ray, checking only that endpoint (in addition to the start) is enough to confirm the entire path stays inside the grid.
Hint 3
Filter aggressively before doing any letter-by-letter comparison: skip any starting cell whose character does not match the first letter of the word, and skip any direction whose endpoint falls outside the grid boundaries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
A DFS with direction-changing at each step solves a different problem (classic path-search). Here the direction is locked after the first step, so the position of every letter is fully determined by three choices: starting row, starting column, and direction. That means the problem is pure enumeration — no search tree, no backtracking.
The k-th letter of a length-L word placed at (r, c) in direction (dr, dc) must sit at:
(r + k*dr, c + k*dc) for k = 0, 1, ..., L-1
Algorithm
- Scan every cell
(r, c). Skip it immediately ifboard[r][c]is notword[0]. - For each of the eight unit directions
(dr, dc):- Compute the endpoint
(r + dr*(L-1), c + dc*(L-1)). - If that endpoint is outside the grid, skip this direction. Because each coordinate changes monotonically along the ray, a valid endpoint guarantees every intermediate cell is also inside the grid — one bounds check replaces L separate checks.
- Walk letters
k = 1throughL-1. On the first mismatch, break early. - If all letters matched, return
True.
- Compute the endpoint
- If no starting cell and direction produced a full match, return
False.
Why it is correct
- Every valid placement is visited: we try every cell as a start and every direction.
- No invalid placement is accepted: we return
Trueonly after confirming all L characters match on a fully in-bounds path. - No wrapping: the endpoint check rejects any ray that would leave the grid. There is no modular indexing.
- No turning: the direction
(dr, dc)is fixed for the entire inner loop. - No revisiting:
(dr, dc)is a nonzero vector, sostart + k*dproduces strictly distinct cells. - Palindromes and reversed words need no special handling. A word read right-to-left is direction
(0, -1), one of the eight tried.
Complexity
Let R × C be the grid dimensions and L = len(word).
- Time: O(R · C · L) in the worst case (a grid of all identical letters with a word that almost matches from every cell). At maximum sizes that is about 100 · 100 · 8 · 100 = 8 × 10⁶ character comparisons, well within typical limits.
- In practice the two early exits (first-letter filter and endpoint bounds check) reject the vast majority of candidates in O(1), so average performance is much better. When L exceeds the longer grid dimension, every direction fails the endpoint check and the cost falls to O(R · C).
- Space: O(1) extra — no recursion stack, no visited set, no copy of the board.
Edge cases
- One-letter word. Any matching cell is enough. The code returns
Truebefore entering the direction loop, avoiding eight trivial iterations. - Word longer than any grid dimension. Every endpoint falls outside the board, so
Falseis returned without comparing any letters. - Non-square grid. Row and column bounds are checked independently, so a 2 × 100 board is handled correctly.
- Partial match near an edge. The endpoint check catches this before any letters are compared, preventing out-of-range indexing.
Full solution
from typing import List
def find_word_in_grid(board: List[str], word: str) -> bool:
if not board or not board[0] or not word:
return False
rows = len(board)
cols = len(board[0])
directions = [
(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1),
]
for r in range(rows):
for c in range(cols):
# Reject cells that don't match the first letter immediately.
if board[r][c] != word[0]:
continue
# A single-letter word is satisfied by any matching cell.
if len(word) == 1:
return True
for dr, dc in directions:
# Check that the final cell of this ray is inside the grid.
# Because each coordinate changes monotonically, this one
# check covers every intermediate cell as well.
end_r = r + dr * (len(word) - 1)
end_c = c + dc * (len(word) - 1)
if not (0 <= end_r < rows and 0 <= end_c < cols):
continue
# Compare the remaining letters along the ray.
matched = True
for k in range(1, len(word)):
if board[r + dr * k][c + dc * k] != word[k]:
matched = False
break
if matched:
return True
return False