Skip to problem
←

Word Search

Medium 0 attempts

You're given an m x n character grid board and a target string word. Return true if word can be traced out by moving through the grid one letter at a time, stepping only to a horizontally or vertically neighboring cell at each move, and never reusing a cell already visited within that same path.

Diagonal moves are not allowed. A path may turn, and repeated letters must use different cells. Matching is case-sensitive.

Function contract

Implement exist(board, word).

Output: Return true if a path spells the entire word, otherwise false.

Example 1

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

Example 2

Input
board = [["A","B"]]
word = "ABA"
Output
false
Visual Aid
Follow neighboring cells
ABDC

ABCD follows right → down → left. Each cell is used once; diagonal steps are not allowed.

Constraints
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consist of lowercase and uppercase English letters
  • board is rectangular and each cell contains one letter.

First reject words longer than the board or needing more copies of a letter than the board contains. These checks avoid expensive searches for impossible inputs.

Iterate through each cell in the grid. If it matches the first character of the word, run DFS to match remaining characters. Mark cells as visited during recursion and restore them on backtrack.

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

  if (word.length > rows * cols) return false;
  const counts = new Map();
  for (const row of board) for (const ch of row) {
    counts.set(ch, (counts.get(ch) || 0) + 1);
  }
  for (const ch of word) {
    if (!counts.get(ch)) return false;
    counts.set(ch, counts.get(ch) - 1);
  }

  function dfs(r, c, idx) {
    if (idx === word.length) return true;
    if (r < 0 || r >= rows || c < 0 || c >= cols || board[r][c] !== word[idx]) return false;

    const temp = board[r][c];
    board[r][c] = '#';

    const found = dfs(r + 1, c, idx + 1) || dfs(r - 1, c, idx + 1) ||
                  dfs(r, c + 1, idx + 1) || dfs(r, c - 1, idx + 1);

    board[r][c] = temp;
    return found;
  }

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (dfs(r, c, 0)) return true;
    }
  }
  return false;
}

Time: O(m·n·3^L) where L is the word length Space: O(L) recursion depth plus a constant-size English-letter frequency map.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript