LeetCode 79: Word Search

An Interactive Visual Explainer

Idea By: Chetan Pachpande | Executed By: Gemini

Back to Home

Problem Description

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. The same letter 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

Complexity Analysis

Time Complexity: O(N * M * 4^L)
Where N x M are board dimensions and L is the word length. We may start a search from any of the N*M cells, and each search can branch up to 4 directions for L steps.

Space Complexity: O(L)
The space is dominated by the recursion stack, which can go as deep as the length of the word.

Intuition

This problem is a classic search scenario perfectly suited for a **Depth First Search (DFS)** with **backtracking**.

  1. Iterate and Initiate: We must try starting a search from every single cell, as the word can begin anywhere.
  2. Depth First Search (DFS): From a valid starting cell, we recursively explore neighbors (up, down, left, right) to find the next character of the word.
  3. Marking (Avoid Reuse): To prevent using the same cell twice in a path, we mark it as visited (e.g., with '#') before exploring from it.
  4. Backtracking: If a path fails, we must "un-mark" the cell, restoring its original character. This allows it to be used in different future paths.

Step-by-Step Code

Live Visualization

Algorithm States

Status: Idle Current Cell: N/A Word Index (i): N/A Temp Char: N/A Result (res): N/A

Call Stack

Stack is empty

Execution Commands