KatInterview

Straight-Line Word Search Across Eight Directions

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashinggridstring-matchingenumeration

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