712253. Word Search

Medium

Word Search

Summary

Given a grid of characters and a list of words, find all occurrences of each word in the grid. The words can be placed horizontally or vertically in the grid.

The problem involves strings, dynamic programming, and recursion, making it a medium-level difficulty problem.

Detailed Explanation

To solve this problem, we will use a combination of dynamic programming and recursion. We will create a 2D array dp where dp[i][j] is true if the character at position (i, j) in the grid can be part of a valid word.

We iterate through each cell in the grid and for each cell, we check all possible words that start from this cell. We use recursion to find all occurrences of a word in the grid.

Here's a step-by-step breakdown of the solution:

  1. Initialize dp with all values set to false.
  2. Iterate through each cell (i, j) in the grid.
  3. For each cell, check if the character at this position is equal to the first character of any word in the list.
  4. If it is, recursively call a function to find all occurrences of this word starting from this position.
  5. If the recursive function returns true, set dp[i][j] to true.
  6. Iterate through each cell again and mark as visited all cells that are part of a valid word.

Time complexity: O(mnw) where m is the number of rows, n is the number of columns, and w is the average length of words in the list. Space complexity: O(m*n) for the dp array.

Optimized Solutions

Java

java
public class WordSearch {
    public static boolean exist(char[][] board, String[] wordList) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] dp = new boolean[m][n];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (exist(board, wordList, i, j, dp)) {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean exist(char[][] board, String[] wordList, int i, int j, boolean[][] dp) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return false;
        }

        if (dp[i][j]) {
            return false;
        }

        char c = board[i][j];
        for (String word : wordList) {
            if (word.startsWith(String.valueOf(c))) {
                if (exist(board, new String[] {word}, i + 1, j, dp)) {
                    return true;
                }
            }
        }

        dp[i][j] = true;

        return false;
    }
}

Python

python
class WordSearch:
    def exist(self, board: List[List[str]], wordList: List[str]) -> bool:
        m, n = len(board), len(board[0])
        visited = [[False for _ in range(n)] for _ in range(m)]

        for i in range(m):
            for j in range(n):
                if self.exist(board, wordList, i, j, visited):
                    return True

        return False

    def exist(self, board: List[List[str]], wordList: List[str], i: int, j: int, visited: List[List[bool]]) -> bool:
        m, n = len(board), len(board[0])

        if i < 0 or i >= m or j < 0 or j >= n:
            return False

        if visited[i][j]:
            return False

        c = board[i][j]
        for word in wordList:
            if word.startswith(str(c)):
                if self.exist(board, [word], i + 1, j, visited):
                    return True
        visited[i][j] = True
        return False

C++

cpp
class WordSearch {
public:
    bool exist(vector<vector<char>>& board, vector<string>& wordList) {
        int m = board.size();
        int n = board[0].size();
        vector<vector<bool>> dp(m, vector<bool>(n));

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (exist(board, wordList, i, j, dp)) {
                    return true;
                }
            }
        }

        return false;
    }

    bool exist(vector<vector<char>>& board, vector<string>& wordList, int i, int j, vector<vector<bool>>& dp) {
        int m = board.size();
        int n = board[0].size();

        if (i < 0 || i >= m || j < 0 || j >= n) {
            return false;
        }

        if (dp[i][j]) {
            return false;
        }

        char c = board[i][j];
        for (string word : wordList) {
            if (word.find(c) == 0) {
                if (exist(board, vector<string>{word}, i + 1, j, dp)) {
                    return true;
                }
            }
        }

        dp[i][j] = true;

        return false;
    }
};

JavaScript

javascript
class WordSearch {
  exist(board, wordList) {
    const m = board.length;
    const n = board[0].length;
    let visited = new Array(m).fill(0).map(() => new Array(n).fill(false));

    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) {
        if (this.exist(board, wordList, i, j, visited)) {
          return true;
        }
      }
    }

    return false;
  }

  exist(board, wordList, i, j, visited) {
    const m = board.length;
    const n = board[0].length;

    if (i < 0 || i >= m || j < 0 || j >= n) {
      return false;
    }

    if (visited[i][j]) {
      return false;
    }

    let c = board[i][j];
    for (let word of wordList) {
      if (word.startsWith(c.toString())) {
        if (this.exist(board, [word], i + 1, j, visited)) {
          return true;
        }
      }
    }

    visited[i][j] = true;

    return false;
  }
}
View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.