KatInterview

79. Word Search

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find if a given word exists in an m x n grid of characters. The word can be formed by moving from one cell to an adjacent cell (horizontally or vertically). A key constraint is that each cell can be used only once in the formation of the word.

Solution

Word Search in Python

class Solution:
    def exist(self, board: list[list[str]], word: str) -> bool:
        rows, cols = len(board), len(board[0])

        def dfs(r, c, k):
            # Base case: Check for boundaries and character match.
            # A cell marked '#' won't match any alphabet, effectively handling visited state.
            if not (0 <= r < rows and 0 <= c < cols and board[r][c] == word[k]):
                return False
            
            # If we've reached the end of the word, we've found a match.
            if k == len(word) - 1:
                return True
            
            # Mark the current cell as visited to avoid reusing it in the same path.
            temp = board[r][c]
            board[r][c] = '#'
            
            # Explore the 4-directional neighbors.
            found = (dfs(r + 1, c, k + 1) or
                     dfs(r - 1, c, k + 1) or
                     dfs(r, c + 1, k + 1) or
                     dfs(r, c - 1, k + 1))
            
            # Backtrack: Restore the original character.
            board[r][c] = temp
            
            return found

        # Try to start the search from every cell.
        for r in range(rows):
            for c in range(cols):
                if dfs(r, c, 0):
                    return True
        
        return False

Word Search in Java

class Solution {
    private char[][] board;
    private int rows;
    private int cols;
    private String word;

    public boolean exist(char[][] board, String word) {
        this.board = board;
        this.rows = board.length;
        this.cols = board[0].length;
        this.word = word;
        
        // Iterate through each cell as a potential start point.
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // Start DFS from (i, j).
                if (dfs(i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean dfs(int r, int c, int k) {
        // Base case 1: Check boundaries.
        if (r < 0 || r >= rows || c < 0 || c >= cols) {
            return false;
        }
        
        // Base case 2: Check if the current cell's character matches the word's character.
        // A cell marked with '#' is considered visited and will not match.
        if (board[r][c] != word.charAt(k)) {
            return false;
        }
        
        // Base case 3: If we have matched the last character of the word, we've found it.
        if (k == word.length() - 1) {
            return true;
        }
        
        // Mark the cell as visited to avoid cycles and reusing cells.
        char temp = board[r][c];
        board[r][c] = '#';
        
        // Explore neighbors: down, up, right, left.
        boolean found = dfs(r + 1, c, k + 1) ||
                      dfs(r - 1, c, k + 1) ||
                      dfs(r, c + 1, k + 1) ||
                      dfs(r, c - 1, k + 1);
                      
        // Backtrack: restore the cell's original character.
        board[r][c] = temp;
        
        return found;
    }
}

Word Search in C++

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int rows = board.size();
        int cols = board[0].size();
        
        // Iterate through each cell of the board as a potential starting point.
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                // Start DFS from (i, j) for the first character of the word.
                if (dfs(board, word, i, j, 0)) {
                    return true;
                }
            }
        }
        
        return false;
    }

private:
    // Helper function to perform DFS/backtracking.
    // r, c: current cell coordinates.
    // k: current character index in the word to match.
    bool dfs(vector<vector<char>>& board, const string& word, int r, int c, int k) {
        // Check if out of bounds or if the character doesn't match.
        if (r < 0 || r >= board.size() || c < 0 || c >= board[0].size() || board[r][c] != word[k]) {
            return false;
        }
        
        // If we have found all characters of the word.
        if (k == word.length() - 1) {
            return true;
        }
        
        // Mark the current cell as visited by changing it to a special character.
        // This prevents using the same cell twice in a single path.
        char temp = board[r][c];
        board[r][c] = '#';
        
        // Explore the 4 adjacent cells (up, down, left, right).
        bool found = dfs(board, word, r + 1, c, k + 1) ||
                     dfs(board, word, r - 1, c, k + 1) ||
                     dfs(board, word, r, c + 1, k + 1) ||
                     dfs(board, word, r, c - 1, k + 1);
        
        // Backtrack: restore the original character on the board.
        // This is crucial so that this cell can be part of other paths.
        board[r][c] = temp;
        
        return found;
    }
};

Word Search in TypeScript

function exist(board: string[][], word: string): boolean {
    const rows = board.length;
    const cols = board[0].length;

    const dfs = (r: number, c: number, k: number): boolean => {
        // Base case 1: Check for boundaries.
        if (r < 0 || r >= rows || c < 0 || c >= cols) {
            return false;
        }

        // Base case 2: Check for character match. A cell marked '#' is visited.
        if (board[r][c] !== word[k]) {
            return false;
        }

        // Base case 3: If we've reached the end of the word, we've found a match.
        if (k === word.length - 1) {
            return true;
        }

        // Mark the current cell as visited.
        const temp = board[r][c];
        board[r][c] = '#';

        // Explore neighbors.
        const found = dfs(r + 1, c, k + 1) ||
                      dfs(r - 1, c, k + 1) ||
                      dfs(r, c + 1, k + 1) ||
                      dfs(r, c - 1, k + 1);

        // Backtrack: Restore the original character.
        board[r][c] = temp;

        return found;
    };

    // Try to start the search from every cell.
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (dfs(i, j, 0)) {
                return true;
            }
        }
    }

    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.