Word Search in Grid

💡Strategies for Solving This Problem

Understanding Word Search Problem

Given a 2D grid of characters and a word, determine if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cells (horizontally or vertically). The same cell cannot be used more than once.

Problem Example

board = [
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED" → True
word = "SEE" → True
word = "ABCB" → False (can't reuse 'B')

Approach: Backtracking with DFS

Key Ideas:

  • Try starting from each cell
  • Use DFS to explore all 4 directions
  • Mark visited cells to avoid reuse
  • Backtrack when path doesn't work

Algorithm Steps

  1. For each cell in grid:
    • If cell matches first character of word, start DFS
  2. DFS recursion:
    • If matched entire word, return True
    • Mark current cell as visited
    • Try all 4 directions (up, down, left, right)
    • If direction matches next character, recurse
    • Unmark cell (backtrack) before returning
  3. Return True if any starting point succeeds

Optimization Techniques

1. Early Termination:

  • If word longer than total cells, return False
  • Count character frequencies, if word has more of any char than board, return False

2. Start from Rare Character:

  • If word[0] appears less than word[-1] in board, reverse word
  • Reduces starting points

3. Visited Marking:

  • Option 1: Modify board (mark with '#' or similar)
  • Option 2: Use separate visited set
  • Option 3: Use bitmask for small boards

Time Complexity

  • Worst Case: O(M * N * 4^L)
    • M * N starting points
    • Each DFS explores up to 4 directions
    • L levels deep (word length)
  • Practical: Much better due to pruning
  • Space: O(L) for recursion stack

Related Problems

  • Word Search II: Find multiple words (use Trie!)
  • Boggle: Find all valid words in dictionary
  • Path Sum in Matrix: Similar DFS pattern
  • Number of Islands: DFS on 2D grid

Asked at: Amazon, Microsoft, Google, Facebook, Apple

Scroll to Top