Ecommet

Word Search

Medium Problem 92 of 151 Java and Python

Problem

Given an m × n grid of characters board and a string word, return true if word exists in the grid.

The word must be built from letters of sequentially adjacent cells (horizontally or vertically). The same cell may not be used more than once.

Example 1

Input
board = [["A","B","C","E"], ["S","F","C","S"], ["A","D","E","E"]], word = "ABCCED"
Output
true

Example 2

Input
same board, word = "SEE"
Output
true

Example 3

Input
same board, word = "ABCB"
Output
false
Why
The B would have to be reused.

Constraints

  • 1 ≤ m, n ≤ 6
  • 1 ≤ word.length ≤ 15

Explanation

Try every cell as a starting point. From a cell matching word[i], explore its four neighbours for word[i + 1]. Mark the cell while it is on the current path so it is not reused, and unmark it when you back out.

Approach 1 · Better

DFS with a visited grid

  • Time O(m · n · 3^L), L = word length
  • Space O(m · n) for the visited grid

Depth-first search from each cell, with a separate boolean grid tracking cells on the current path.

  1. For each cell, run dfs(r, c, 0).
  2. dfs: fail if out of bounds, visited, or the letter does not match word[i]; succeed if i is the last index.
  3. Mark visited, try the four neighbours with i + 1, then unmark.
Java
class Solution {
    public boolean exist(char[][] board, String word) {
        boolean[][] visited = new boolean[board.length][board[0].length];
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                if (dfs(board, word, visited, r, c, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, boolean[][] visited, int r, int c, int i) {
        if (r < 0 || c < 0 || r >= board.length || c >= board[0].length
            || visited[r][c] || board[r][c] != word.charAt(i)) {
            return false;
        }
        if (i == word.length() - 1) {
            return true;
        }
        visited[r][c] = true;
        boolean found = dfs(board, word, visited, r + 1, c, i + 1) || dfs(board, word, visited, r - 1, c, i + 1)
            || dfs(board, word, visited, r, c + 1, i + 1) || dfs(board, word, visited, r, c - 1, i + 1);
        visited[r][c] = false;
        return found;
    }
}
Python
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        visited = [[False] * n for _ in range(m)]

        def dfs(r, c, i):
            if not (0 <= r < m and 0 <= c < n) or visited[r][c] or board[r][c] != word[i]:
                return False
            if i == len(word) - 1:
                return True
            visited[r][c] = True
            found = dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)
            visited[r][c] = False
            return found

        return any(dfs(r, c, 0) for r in range(m) for c in range(n))

Approach 2 · Optimal

In-place marking with pruning

  • Time O(m · n · 3^L)
  • Space O(L) recursion

Mark a cell by overwriting it with # while it is on the path, so no extra grid is needed. Before searching, check the board has enough of each letter.

  1. If the board does not contain enough copies of some letter of word, return false straight away.
  2. Run the same DFS, but set board[r][c] = '#' while visiting and restore it afterwards.
Java
class Solution {
    public boolean exist(char[][] board, String word) {
        int[] have = new int[128];
        for (char[] row : board) {
            for (char ch : row) {
                have[ch]++;
            }
        }
        for (char ch : word.toCharArray()) {
            if (--have[ch] < 0) {
                return false;
            }
        }
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                if (dfs(board, word, r, c, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, int r, int c, int i) {
        if (r < 0 || c < 0 || r >= board.length || c >= board[0].length || board[r][c] != word.charAt(i)) {
            return false;
        }
        if (i == word.length() - 1) {
            return true;
        }
        char saved = board[r][c];
        board[r][c] = '#';
        boolean found = dfs(board, word, r + 1, c, i + 1) || dfs(board, word, r - 1, c, i + 1)
            || dfs(board, word, r, c + 1, i + 1) || dfs(board, word, r, c - 1, i + 1);
        board[r][c] = saved;
        return found;
    }
}
Python
from collections import Counter

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m, n = len(board), len(board[0])
        have = Counter(ch for row in board for ch in row)
        if any(have[ch] < need for ch, need in Counter(word).items()):
            return False

        def dfs(r, c, i):
            if not (0 <= r < m and 0 <= c < n) or board[r][c] != word[i]:
                return False
            if i == len(word) - 1:
                return True
            saved, board[r][c] = board[r][c], "#"
            found = dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)
            board[r][c] = saved
            return found

        return any(dfs(r, c, 0) for r in range(m) for c in range(n))

Complexity compared

ApproachTimeSpace
Better DFS with a visited gridO(m · n · 3^L), L = word lengthO(m · n) for the visited grid
Optimal In-place marking with pruningO(m · n · 3^L)O(L) recursion

Key takeaways

  • Always restore the cell after exploring, even when the search succeeded, if the caller still needs the board.
  • Another cheap pruning: if the last letter of the word is rarer on the board than the first, search the reversed word.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem