📖 4 min read
Last updated on

Word Search — Coding Interview Walkthrough


You’re in a coding interview. The interviewer says: “Given a 2D board and a word, determine if the word exists in the grid by traversing adjacent cells without reusing a cell.” This is DFS with backtracking on a grid. The key: mark cells as visited during the search and unmark them after — that’s the backtracking step.


Already know how to solve Word Search? Try a Word Search mock interview on Intervu →

The Problem

Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word must be constructed from sequentially adjacent cells (horizontally or vertically). The same 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

3×4 character grid with DFS path A→B→C→C→E→D highlighted in teal, showing the backtracking search path for 'ABCCED'.

What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
DFS + backtrackingDo you use the mark/unmark visited pattern?
Early terminationDo you check character match before recursing?
All starting cellsDo you try DFS from every matching first character?
In-place markingDo you mark cells in place vs. separate set?

Step 1: The Key Insight

DFS + backtracking: mark a cell as visited before exploring neighbors, then unmark after (whether you succeed or fail). This lets other paths reuse cells from dead-end branches. Try every cell as a potential starting point.


Python Implementation

def exist(board: list[list[str]], word: str) -> bool:
    rows, cols = len(board), len(board[0])
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    def dfs(r: int, c: int, index: int) -> bool:
        if index == len(word):
            return True
        if r < 0 or r >= rows or c < 0 or c >= cols:
            return False
        if board[r][c] != word[index]:
            return False

        temp = board[r][c]
        board[r][c] = '#'  # mark visited

        for dr, dc in directions:
            if dfs(r + dr, c + dc, index + 1):
                board[r][c] = temp
                return True

        board[r][c] = temp  # unmark — backtrack
        return False

    for r in range(rows):
        for c in range(cols):
            if dfs(r, c, 0):
                return True
    return False

Time & Space Complexity

AspectComplexity
TimeO(m × n × 4^L) — L is word length
SpaceO(L) — recursion stack

Common Interview Mistakes

  1. Not unmarking visited cells. Other paths can’t reuse cells from dead-end branches. Always restore.
  2. Wrong early-exit order. Check bounds and character match before accessing board[r][c].
  3. Not trying all starting cells. Must iterate every cell as a potential start.

What a Strong Candidate Sounds Like

“For each cell, I run DFS matching character by character. I mark cells visited in-place with ’#’, restore after recursion — that’s the backtracking. I return true as soon as any path completes the word. Time is O(m·n·4^L), space O(L).”



Frequently Asked Questions

Depth-First Search coupled with aggressive Backtracking drives the matrix exploration perfectly. You plunge forward searching adjacent cells character-by-character along an assumed correct path. If a branch inevitably hits dead-end non-matching letters, you immediately backtrack backwards to explore alternative valid routes cleanly.

How do you prevent identical grid blocks from artificially looping?

As the algorithm traverses forward matching characters, you dynamically modify the active coordinate value locally into a distinct visited symbol (like #). Upon backtracking from a failed deeper plunge, you simply restore the original legitimate character backwards, naturally opening that block again for entirely separate pathway scans.

Practice This in a Mock Interview

Start a mock interview for Word Search on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →