Problem Overview
- We are given a 2D array of characters named
board. - The board size is
m x n. - We are also given a string
word. - Our goal is to find whether the word exists in the board.
- If found → return
true, otherwise → returnfalse.
Example
| |

Intuition
First, we need to find
word[0]in the matrix.If we find it, we start searching in four directions using recurrsion
- Top
- Bottom
- Left
- Right
From there, we search for the next character.
If it matches, we continue recursively.
If we reach the last character → return
true.
This problem is combination DFS and Backtracking .
Approach
Base Solution — DFS + Backtracking
| |
Optimized Version
What We Improve
Frequency Pruning
- If the board does not contain required characters → return
falseearly. - This avoids unnecessary recursion.
- If the board does not contain required characters → return
Start from the Rarer Character
- If the last character appears less frequently than the first character,
- Reverse the word.
- This reduces branching and recursion calls.
Optimized Code
| |
Time and Space Complexity
- Time: O(m × n × 4^L)
Where:
m × n→ possible starting pointsL→ length of word4^L→ exploring 4 directions recursively
With pruning, average performance improves significantly.
- Space: O(L)
- Due to recursion stack
- No extra data structures used apart from frequency array
Final Takeaways
Always break the problem into smaller subproblems.
In recursion, always handle exit/base conditions carefully.
Backtracking means:
- Mark
- Explore
- Restore
Try to reduce unnecessary recursive calls using pruning.
Grid + word search problems → Think DFS + Backtracking first.
