Search a Word in a 2D Grid of characters

Pattern: Word search

medium

The word must lie in a straight line in one of 8 directions. From each cell, try each direction and compare the letters one by one. Record the cell if any direction matches.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a grid of letters and a word, return every cell from which the word can be read in a straight line in any of the 8 directions (horizontal, vertical or diagonal, forwards or backwards). Return the cells as [row, col] pairs in row-major order, each once. For example, in the grid GEEKSFORGEEKS / GEEKSQUIZGEEK / IDEQAPRACTICE, GEEKS starts at [0, 0], [0, 8] and [1, 0].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name searchWord is this guide's own.

Think first

  • How is a straight line different from a path that can turn?
  • How many directions are there?
  • When should you stop checking one direction?

Hints

    Brute force, and why it fails

    This is already direct: R × C starts, 8 directions, up to L letters each.

    The key insight

    Unlike Word Search, a straight line has no choices along the way, so the "search" is just a loop over the letters.

    Dry run

    A B C0 
    D E F1 
    G H I2 

    The grid rows are ABC, DEF and GHI, and the word is AEI.

    Step 1 of 4

    The plan

    for each cell (r, c):
        for each of the 8 directions (dr, dc):
            if every i has grid[r + dr*i][c + dc*i] == word[i] inside the grid:
                record [r, c]; stop trying directions
    

    Complexity

    Time
    O(R × C × 8 × L)
    Space
    O(1)

    Each start tries 8 directions of up to L letters. Only the output is stored.

    Edge cases

    • A one-letter word: every cell with that letter.
    • A palindrome: the same cell may match in two directions but is recorded once.
    • Words longer than the grid in every direction: no matches.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private static final int[] DR = {-1, -1, -1, 0, 0, 1, 1, 1}, DC = {-1, 0, 1, -1, 1, -1, 0, 1};
    
        public List<int[]> searchWord(char[][] grid, String word) {
            List<int[]> out = new ArrayList<>();
            for (int r = 0; r < grid.length; r++)
                for (int c = 0; c < grid[0].length; c++)
                    for (int k = 0; k < 8; k++) {           // try all 8 straight directions
                        if (straight(grid, word, r, c, k)) { out.add(new int[]{r, c}); break; }
                    }
            return out;                                     // cells in row-major order
        }
    
        private boolean straight(char[][] g, String w, int r, int c, int k) {
            for (int i = 0; i < w.length(); i++) {
                int nr = r + DR[k] * i, nc = c + DC[k] * i;
                if (nr < 0 || nc < 0 || nr >= g.length || nc >= g[0].length || g[nr][nc] != w.charAt(i)) return false;
            }
            return true;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> searchWord(vector<vector<char>>& grid, string word) {
            static const int DR[8] = {-1, -1, -1, 0, 0, 1, 1, 1}, DC[8] = {-1, 0, 1, -1, 1, -1, 0, 1};
            int R = static_cast<int>(grid.size()), C = static_cast<int>(grid[0].size());
            vector<vector<int>> out;
            for (int r = 0; r < R; r++)
                for (int c = 0; c < C; c++)
                    for (int k = 0; k < 8; k++) {           // try all 8 straight directions
                        bool ok = true;
                        for (size_t i = 0; i < word.size() && ok; i++) {
                            int nr = r + DR[k] * static_cast<int>(i), nc = c + DC[k] * static_cast<int>(i);
                            ok = nr >= 0 && nc >= 0 && nr < R && nc < C && grid[nr][nc] == word[i];
                        }
                        if (ok) { out.push_back({r, c}); break; }
                    }
            return out;                                     // cells in row-major order
        }
    };

    Python

    class Solution:
        DIRS = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
    
        def searchWord(self, grid: list[list[str]], word: str) -> list[list[int]]:
            R, C = len(grid), len(grid[0])
            out = []
            for r in range(R):
                for c in range(C):
                    for a, b in self.DIRS:          # try all 8 straight directions
                        if all(0 <= r + a * i < R and 0 <= c + b * i < C and grid[r + a * i][c + b * i] == word[i]
                               for i in range(len(word))):
                            out.append([r, c])
                            break
            return out                              # cells in row-major order

    Common mistakes

    • Recording a cell once per matching direction.
    • Letting the line wrap around the edge of the grid.
    • Allowing turns, which turns this into Word Search.

    Similar problems