Leetcode #79: Word Search
In this guide, we solve Leetcode #79 Word Search in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Array, String, Backtracking, Matrix
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Python Solution
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(i: int, j: int, k: int) -> bool:
if k == len(word) - 1:
return board[i][j] == word[k]
if board[i][j] != word[k]:
return False
c = board[i][j]
board[i][j] = "0"
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = i + a, j + b
ok = 0 <= x < m and 0 <= y < n and board[x][y] != "0"
if ok and dfs(x, y, k + 1):
return True
board[i][j] = c
return False
m, n = len(board), len(board[0])
return any(dfs(i, j, 0) for i in range(m) for j in range(n))
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.