Word Search (LeetCode 79): Solution and Explanation

Medium
Array
String
Backtracking
Matrix

Given a grid of letters and a target word, decide whether the word can be spelled by moving between horizontally or vertically adjacent cells. Each cell can be used at most once within a single spelling of the word.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The word could start at any cell, and from each letter it could continue in up to four directions. There is no ordering or structure in the grid to exploit, so some form of exhaustive search is unavoidable. The goal is to make that search systematic and to cut off dead branches as early as possible.

Depth-first search with backtracking fits naturally. From a starting cell, you try to match word[0], then step to a neighbor and try to match word[1], and so on. If a cell is out of bounds, holds the wrong letter, or is already part of the current path, that branch dies immediately. If you match all L characters, you are done.

The detail that makes it correct is the visited set. A cell used earlier in the current path cannot be reused, but the same cell is perfectly fine for a different path that starts elsewhere or branches differently. So you add the cell to path before exploring its neighbors and remove it afterward. That undo step is the backtracking, and it is what lets one shared set serve every branch of the search.

Approach: Backtracking DFS from every cell

  1. Record ROWS and COLS and create an empty set path for cells used in the current attempt.
  2. Define dfs(r, c, i), which tries to match word[i:] starting at cell (r, c). If i == len(word), every character matched, so return True.
  3. Return False if the cell is out of bounds, its letter differs from word[i], or it is already in path.
  4. Add (r, c) to path, then try the four neighbors with i + 1, stopping at the first success because of short-circuit or.
  5. Remove (r, c) from path before returning so other branches can use it.
  6. Call dfs(r, c, 0) from every cell and return True as soon as one succeeds, or False after trying them all.

Step-by-step example

board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
  1. Start at (0,0), which holds A and matches word[0]. The downward neighbor S does not match B, and up is out of bounds, so the search tries right.
  2. (0,1) holds B, which matches. From there, down is F (no), up is out of bounds, and right is (0,2) holding C, which matches word[2].
  3. From (0,2), moving down reaches (1,2), which holds C and matches word[3].
  4. From (1,2), moving down reaches (2,2), which holds E and matches word[4].
  5. From (2,2), down is out of bounds, up is (1,2) already in path, right is E (no), and left is (2,1) holding D, which matches word[5].
  6. The next call has i equal to 6, the length of the word, so it returns True and the whole search succeeds.

Code: Python, Java, C++

1class Solution:
2    def exist(self, board: List[List[str]], word: str) -> bool:
3        ROWS, COLS = len(board), len(board[0])
4        path = set()
5        
6        def dfs(r, c, i):
7            if i == len(word):
8                return True
9            if (r < 0 or c < 0 or r >= ROWS or c >= COLS or
10                word[i] != board[r][c] or (r, c) in path):
11                return False
12            
13            path.add((r, c))
14            res = (dfs(r + 1, c, i + 1) or
15                   dfs(r - 1, c, i + 1) or
16                   dfs(r, c + 1, i + 1) or
17                   dfs(r, c - 1, i + 1))
18            path.remove((r, c))
19            return res
20            
21        for r in range(ROWS):
22            for c in range(COLS):
23                if dfs(r, c, 0): return True
24        return False

Time and space complexity

Time

O(m × n × 3^L)

Each of the m × n cells can start a search. After the first step, a path never usefully moves back to the cell it came from, so it branches into at most 3 new directions per character, over L characters.

Space

O(L)

The recursion depth and the path set both hold at most L cells, one for each matched character.

Other approaches

In-place marking instead of a set (time O(m × n × 3^L), space O(L))

Temporarily overwrite board[r][c] with a sentinel such as # while it is on the path and restore it afterward. It saves the hashing cost of a set and uses no extra memory beyond the recursion stack.

Pruning with letter counts (time O(m × n × 3^L), space O(L))

Before searching, count letters in the board and fail fast if the word needs more of any letter than exists. If the last letter of the word is rarer than the first, search the reversed word to reduce branching. The worst case is unchanged, but real inputs run much faster.

Common mistakes

  • Forgetting to remove the cell from path after exploring it. Then cells stay blocked for later branches and valid words are missed.
  • Checking (r, c) in path before the bounds check in a language that indexes the board first, which can cause an index error.
  • Using a global visited set that is never reset between different starting cells.
  • Allowing diagonal moves. Only the four orthogonal neighbors count.

Frequently asked questions

What is the time complexity of Word Search?

It is O(m × n × 3^L), where L is the length of the word. Every cell can start a search, and each step of the path branches into at most three unvisited directions.

Why is backtracking needed in Word Search?

A cell may be used only once per path, but a cell that fails in one path might be needed in another. Marking it while it is in use and unmarking it afterward enforces the rule without blocking other attempts.

How does Word Search II differ?

Word Search II asks for many words at once. Running this search separately for each word is too slow, so the usual solution builds a trie of all words and runs one DFS over the board that follows trie edges.