Word Search solution explained

To check whether a word can be traced on a letter grid, try every cell as a start and run a depth-first search that matches one letter per step, moves only up, down, left or right, temporarily marks the current cell as used, and undoes the mark when it backtracks. The search stops at the first full match. Worst case is about O(R × C × 3^L) for a word of length L, and two cheap checks (letter counts and starting from the rarer end) cut most real cases down sharply.

By Published 7 min read

The problem, in plain terms

You have a rectangular board where every cell holds one letter, and a word. Decide whether you can spell the word by starting on some cell and stepping to a horizontally or vertically adjacent cell for each next letter. Diagonal moves are not allowed, and a single cell cannot be used twice in the same word.

T R A P
O E I N
S N A G

TRAIN -> true   T R A along the top row, then down to I, right to N
REIN  -> true   R, down to E, right to I, right to N
NEN   -> false  the only N next to E is the one already used
TREE  -> false  the board has a single E
An example board, made up for this page

Clarify the board size and the word length, whether letters are case-sensitive, and whether you may modify the board temporarily (most interviewers say yes, as long as you restore it).

How the problem is used in interviews

Word Search is the standard introduction to backtracking on a grid. Interviewers watch for the three parts every backtracking answer needs: a clear base case, a choose-recurse-undo loop, and correct bookkeeping of what is in use on the current path. It also gives room to talk about pruning and about why the worst case is exponential in the word length.

A slower starting idea

The naive version explores every path from every cell, carrying a fresh copy of the set of visited cells into each recursive call and only comparing letters at the end. Copying the set costs O(L) per step and checking late explores paths that were dead from the first wrong letter. Comparing the letter before stepping, and marking and unmarking a single shared board, turns the same search into the standard solution.

The optimal approach: depth-first backtracking with in-place marks

For each cell, call a search with the index of the letter to match. If the cell is off the board, already used, or holds the wrong letter, fail. If it matches the last letter, succeed. Otherwise mark it used, try the four neighbors with the next index, then restore the cell whether or not a neighbor succeeded. Before any of that, count letters: if the word needs three Es and the board has two, there is nothing to search. And if the word's last letter appears less often on the board than its first, search for the reversed word, which starts from fewer cells.

from collections import Counter

def exist(board, word):
    rows, cols = len(board), len(board[0])
    # Prune: the board must hold enough of every letter.
    have = Counter(ch for row in board for ch in row)
    if any(have[ch] < n for ch, n in Counter(word).items()):
        return False
    # Start from the rarer end; fewer starting cells means fewer dead ends.
    if have[word[0]] > have[word[-1]]:
        word = word[::-1]

    def dfs(r, c, i):
        if board[r][c] != word[i]:
            return False
        if i == len(word) - 1:
            return True
        saved, board[r][c] = board[r][c], None      # mark as used on this path
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and dfs(nr, nc, i + 1):
                board[r][c] = saved
                return True
        board[r][c] = saved                          # undo before backtracking
        return False

    return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
Python: backtracking with two up-front prunes. The board is restored before returning.
function exist(board, word) {
  const rows = board.length, cols = board[0].length;
  const steps = [[1, 0], [-1, 0], [0, 1], [0, -1]];

  function dfs(r, c, i) {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return false;
    if (board[r][c] !== word[i]) return false;     // also rejects used cells
    if (i === word.length - 1) return true;
    const saved = board[r][c];
    board[r][c] = "";                              // mark as used on this path
    let found = false;
    for (const [dr, dc] of steps) {
      if (dfs(r + dr, c + dc, i + 1)) { found = true; break; }
    }
    board[r][c] = saved;                           // undo before returning
    return found;
  }

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (dfs(r, c, 0)) return true;
    }
  }
  return false;
}
JavaScript: the core search without the prunes, bounds checked at the top of each call.

Overwriting the cell with a value no letter can equal (None in Python, an empty string in JavaScript) means the letter comparison also rejects used cells, so no separate visited structure is needed. Recursion depth is at most the word length, so stack limits are not a concern here unless words can be thousands of letters long.

Complexity summary

R rows, C columns, word length L
ApproachTime (worst case)Extra space
Explore all paths, copy visited sets, check at the endO(R × C × 4^L × L)O(L²) across the path's copies
Backtracking with in-place marksO(R × C × 3^L)O(L) recursion
Same, with letter-count and rarer-end prunesSame bound, far faster on typical boardsO(alphabet) for the counts
R rows, C columns, word length L. Scroll sideways on a small screen.

Each step after the first has at most three new directions, because the cell you came from is marked, which is where 3^L comes from. The exponent is why interviewers ask about pruning: without pruning, the worst case is easy to trigger, for instance with a board full of the same letter and a word that is that letter repeated with a different letter at the end.

Edge cases to try

  • A one-cell board, with a one-letter word that matches and one that does not.
  • A word longer than the number of cells.
  • A word that would need to reuse a cell, like NEN above.
  • A board of identical letters, the slow case for unpruned search.
  • A word that appears only reversed along a path, to test the rarer-end swap.

Pitfalls

  • Forgetting to restore a cell on the success path, which leaves the board modified for the caller.
  • Checking bounds after indexing the board, which crashes or wraps around with negative indexes in Python.
  • Allowing diagonal moves when the problem does not.
  • Keeping one visited set for the whole board instead of per path, which wrongly blocks valid paths that share cells with failed ones.
  • Not stopping once a match is found, so the search keeps exploring.

How to explain it out loud

Fictional example

Walking an interviewer through the backtracking
Candidate
I'll try each cell as a start and do a depth-first search that matches one letter per step. At each cell I check bounds and the letter, then mark the cell so this path can't reuse it, try the four neighbors, and unmark it on the way back.
Candidate
The mark is just overwriting the letter with something no letter equals, so I don't need a separate visited set. Depth is at most the word length.
Candidate
Worst case is exponential in the word length, about R times C times three to the L. Two cheap prunes help a lot: if the board doesn't have enough of some letter I return false immediately, and I search from whichever end of the word is rarer on the board.

When the task changes to finding many words on one board, running this search once per word gets slow. Word Search II combines the same backtracking with a prefix tree, which you can build first in Implement Trie.

Natively as a practice aid

Backtracking explanations tend to skip the undo step when you are nervous. While you practice on Mac or Windows, Natively can read the board and word from a screenshot, suggest the search and prunes, and help debug a failing case. Its transcript of the session lets you check afterward whether you said where the mark is removed. Read about the AI interview assistant.

Questions people ask

How do you solve Word Search?

Try every cell as a starting point and run a depth-first search that matches one letter per step, moves only to adjacent cells, marks the current cell as used, and restores it when backtracking. Return true at the first full match.

What is the time complexity of Word Search?

About O(R × C × 3^L) in the worst case for an R by C board and a word of length L, since each step after the first has at most three unused directions. Extra space is O(L) for the recursion.

How can you speed up Word Search?

Return false immediately if the board lacks enough copies of any letter, and search for the reversed word when its last letter is rarer on the board than its first.

Do I need a visited array for Word Search?

Not necessarily. Temporarily overwrite the current cell with a value no letter can equal, then restore it on the way back. It must be tracked per path, not for the whole board.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP