InterviewPrepKit

Home / Coding / Backtracking

Word Search

medium Original β†—
Solving tips
  • Grid-path backtracking: DFS from every cell, matching one character at a time so a mismatch (board[r][c] != word[i]) kills the branch immediately.
  • Encode 'visited' by overwriting the cell with a sentinel like '#' before recursing and restoring it on unwind, giving O(1) space instead of a visited set.
  • Restore the cell on EVERY return path, including early success returns, or corrupted state breaks other starting positions.
  • Time is O(m*n * 3^L) (three onward directions per step), O(L) stack; bonus prunes: reject if the board lacks required letter counts, and anchor the search on the rarer end of the word.

Problem

You are given an m x n grid of characters board and a string word. Decide whether word can be spelled out by walking through the grid: start at any cell, and at each step move to a cell that shares an edge with the current one (up, down, left, or right β€” no diagonals). The path must spell word in order, and a cell may be used at most once within a single path. Return True if such a path exists, else False.

Examples

Board used in all three examples:

A B C E
S F C S
A D E E
  • word = "ABCCED" β†’ True β€” path: (0,0) β†’ (0,1) β†’ (0,2) β†’ (1,2) β†’ (2,2) β†’ (2,1).
  • word = "SEE" β†’ True β€” path: (1,3) β†’ (2,3) β†’ (2,2), starting from the right-side S.
  • word = "ABCB" β†’ False β€” the only B adjacent to the C path is the one already used, and reuse is forbidden.

Constraints

  • 1 <= m, n <= 6 β€” at most 36 cells.
  • 1 <= word.length <= 15
  • Board and word consist of uppercase and lowercase English letters.
  • The tiny bounds signal an exponential search: up to mΒ·n starts times roughly 3^L branching (L = word length), so aggressive pruning is what makes it fast in practice.

Think about it first

Hint 1 From a given starting cell, how would you explore all paths of length `len(word)`? What choice do you make at each step, and what must you undo when you back out of a dead end?
Hint 2 Don't build whole paths and compare at the end. Match one character at a time: if the current cell doesn't equal `word[i]`, abandon this branch immediately β€” that mismatch check is the pruning that collapses the search tree.
Hint 3 You need to mark cells as "in use" along the current path. Instead of carrying a visited set, overwrite the cell with a sentinel like `"#"` before recursing and restore the original letter afterward β€” O(1) space and it can never match a real letter. Bonus prunes: bail out early if the board lacks enough of some letter in `word`, and search from the rarer end of the word.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.