Skip to main content

Word Search

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. The same letter cell may not be used more than once.

  • Example:

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

โœ… Solution: Backtracking (DFS on Grid)โ€‹

class Solution {
public:
// Recursive DFS to match characters in all 4 directions
bool searchNext(vector<vector<char>> &board, string word, int row, int col, int index, int m, int n){
if(index == word.length()) return true;

// Out of bounds or mismatch or visited cell
if(row < 0 || col < 0 || row >= m || col >= n || board[row][col] != word[index] || board[row][col] == '!'){
return false;
}

char c = board[row][col]; // Save the current character
board[row][col] = '!'; // Mark as visited

// Explore in all four directions
bool up = searchNext(board, word, row - 1, col, index + 1, m, n);
bool down = searchNext(board, word, row + 1, col, index + 1, m, n);
bool left = searchNext(board, word, row, col - 1, index + 1, m, n);
bool right = searchNext(board, word, row, col + 1, index + 1, m, n);

board[row][col] = c; // Unmark (Backtrack)
return up || down || left || right;
}

bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
int n = board[0].size();

// Try every cell as a starting point
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == word[0]){
if(searchNext(board, word, i, j, 0, m, n))
return true;
}
}
}
return false;
}
};


๐Ÿ“ How It Worksโ€‹

  • We're given a 2D grid board and a string word.
  • The goal is to check whether word can be formed by starting from any cell and moving up, down, left, or right without revisiting any cell.
  • The searchNext function is a DFS that:
    1. Checks base case: if index == word.length() โ†’ word is matched.
    2. Bounds check and visited check (board[row][col] == '!').
    3. Temporarily marks current cell as visited by setting it to '!'.
    4. Tries all 4 directions recursively.
    5. Backtracks by restoring the cell's original character.

๐Ÿงฉ Key Formula / Recurrenceโ€‹

searchNext(row, col, index) =
searchNext(row + 1, col, index + 1) ||
searchNext(row - 1, col, index + 1) ||
searchNext(row, col + 1, index + 1) ||
searchNext(row, col - 1, index + 1)


โฑ๏ธ Time & Space Complexityโ€‹

๐Ÿ”ธ Time Complexity: O(M ร— N ร— 4^L)โ€‹

Where:

  • M = number of rows in the board
  • N = number of columns
  • L = length of the word

Explanation:

  • You try starting from every cell โ†’ M ร— N calls.
  • For each call, you may explore up to 4 directions (up/down/left/right).
  • In the worst case, from each step you explore 4 more paths โ†’ up to 4^L recursive calls per path.

โœ… Total worst-case time = O(M ร— N ร— 4^L)


๐Ÿ”ธ Space Complexity: O(L)โ€‹

Why?

  • The recursion depth is equal to L (the word length), as each recursive call adds 1 letter.
  • We do in-place marking (board[row][col] = '!') to avoid using extra space for a visited matrix.

โœ… Total space = O(L) for the call stack


โš ๏ธ Edge Casesโ€‹

  • Empty grid or empty word โ†’ return false
  • Word longer than total grid cells โ†’ can't be matched
  • Grid with same repeating letters โ†’ handled via visited marking

๐Ÿ’ก Other Approachesโ€‹

ApproachTimeUse Case
Trie + DFS (Word Search II)O(M ร— N ร— L ร— 4^L)Optimized for multiple word queries
Iterative DFS/BFSSimilarHarder to implement due to visited tracking

  • Leetcode 79. Word Search โœ… (this one)
  • Leetcode 212. Word Search II ๐Ÿ”ฅ (uses Trie)
  • Leetcode 200. Number of Islands
  • Leetcode 694. Number of Distinct Islands

Let me know if you want the optimized Trie-based version for multiple word searches (Leetcode 212)!

๐Ÿš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Serverโ†’
โšก
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

๐Ÿ’กHave handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contributeโ†’