InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Word Search

medium Original ↗ 00:00

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 main pruning step.
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. Additional pruning: stop early if the board lacks enough of some letter in `word`, and start the search from the rarer end of the word.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug