Word Path Search on a Grid
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given a rectangular 2D character array board with rows rows and cols columns, along with a target string word. Each entry board[r][c] holds a single character.
Implement exists(board, word) -> bool to decide whether word can be traced along a sequence of orthogonally neighboring grid squares:
- Every step between consecutive letters of
wordmust move up, down, left, or right by one square (diagonal moves are disallowed). - Within a single candidate path, each
(row, col)cell may be visited at most once. - Character matching is case-sensitive (
"a"and"A"are distinct). - When
existsfinishes,boardmust retain its exact original contents (any temporary in-place edits made during exploration must be undone before returning). - An empty target (
word == "") requires zero cells and always evaluates toTrue, whereas a non-emptywordon an empty grid ([]or[[]]) evaluates toFalse.
Examples
Example 1
Input:
board = [
["T", "U", "N", "K"],
["R", "O", "N", "P"],
["M", "L", "E", "P"]
]
word = "TUNNEL"
Output: True
Explanation: Starting at (0, 0) = "T", moving right to (0, 1) = "U", right to (0, 2) = "N", down to (1, 2) = "N", down to (2, 2) = "E", and left to (2, 1) = "L" spells "TUNNEL" using six distinct orthogonally connected cells.
Example 2
Input:
board = [
["T", "U", "N", "K"],
["R", "O", "N", "P"],
["M", "L", "E", "P"]
]
word = "NONE"
Output: False
Explanation: Although the grid contains two "N"s, one "O", and one "E", no legal path spells "NONE". Starting at (0, 2) = "N" has no adjacent "O". Starting at (1, 2) = "N" and stepping left to (1, 1) = "O" gets stuck: stepping right back onto (1, 2) would reuse an already visited square, and the other "N" at (0, 2) sits diagonally from (1, 1).
Example 3
Input:
board = [
["c", "c"],
["t", "z"]
]
word = "cct"
Output: True
Explanation: Trying (0, 0) -> (0, 1) reaches a dead end because (1, 1) holds "z". Backtracking and starting instead at (0, 1) = "c", moving left to (0, 0) = "c", and moving down to (1, 0) = "t" spells "cct".
Constraints
0 <= len(board) <= 120 <= len(board[r]) <= 12, and all rows have identical length- Every cell
board[r][c]is a 1-character string (letters, digits, or symbols; comparisons are case-sensitive) 0 <= len(word) <= 150boardmust remain unmodified afterexists(board, word)returns
Step-by-step walkthrough
Understand the rules and boundary cases
We are given a rectangular
rows x colsgridboardof single-character strings and a target stringword. We wantexists(board, word)to returnTrueif we can spellwordby walking from square to square under three rules:- Orthogonal moves only: each step moves up, down, left, or right (diagonals are not allowed).
- No cell reuse within a path: a single path cannot step onto the same
(row, col)square twice, though two separate path attempts may try the same square. - Exact, non-destructive check: comparisons are case-sensitive (
"a" != "A"), and even if we temporarily editboardduring the search,boardmust look identical whenexistsreturns.
Board: Valid path for "pqsr": Invalid for "ps" (diagonal) p q (0,0) -> (0,1) -> (1,1) Invalid for "pqp" (reuses (0,0)) r s -> (1,0)Before writing the search, lock down the boundary cases: - If
word == "", zero letters are needed, so the empty path immediately succeeds (True). - Otherwise, ifboardhas zero rows ([]) or zero columns ([[]]), no letters exist, so returnFalse.Why enumerating every path first is wasteful
A naive brute-force plan generates every non-overlapping path of length
L = len(word)on the grid and checks whether any path's letters equalword. How fast does the number of paths grow?A word of
Lletters visitsLcells joined byL - 1steps: - Step 1 from the starting cell can move in at most 4 directions. - Each of the remainingL - 2steps can move in at most 3 new directions, because stepping straight back onto the previous cell is forbidden.That means up to
4 * 3^(L - 2)paths per starting cell (forL >= 2). Generating all of them when the very first cell does not even matchword[0]wastes almost all of the work.Instead, we use backtracking — a search strategy that builds a candidate path one step at a time and abandons ("backs out of") a branch the instant a letter fails to match. Most wrong branches die on the first or second character instead of growing to length
L.Frame one recursive question per cell
We can express the whole search with a single helper function,
_match_from(board, word, index, row, col), which answers one focused question:Can the remaining suffix
word[index:]be spelled starting at(row, col)without stepping onto any cell already used earlier in the current path?Let's check what happens at
(row, col)in order: 1. Out of bounds: ifrow < 0,row >= len(board),col < 0, orcol >= len(board[0]), we stepped off the grid, so returnFalse. (In Python, we must check< 0explicitly becauseboard[-1]silently wraps around to the last row!) 2. Letter mismatch: ifboard[row][col] != word[index], this cell cannot supply the next letter, so returnFalse. 3. Finished the word: ifindex == len(word) - 1, we just matched the final character ofword, so returnTrue! 4. Recurse to neighbors: mark(row, col)as used on the current path, try matchingindex + 1at each of the 4 orthogonal neighbors (DIRECTIONS), unmark(row, col), and return whether any neighbor succeeded.Mark visited cells in place and always restore them
Normally, depth-first search (DFS, exploring as deep as possible along one branch before backing up) tracks the active path in a separate
rows x colsbooleanvisitedgrid. We can avoid thatO(rows * cols)matrix by marking the board in place:- What sentinel value is safe? Every
word[index]is a 1-character string (len == 1). If we temporarily overwriteboard[row][col]with the empty stringVISITED = ""(len == 0), thenboard[row][col] != word[index]is guaranteed to beTruefor any characterwordmight contain (even#, digits, or punctuation!). So our existing mismatch check automatically rejects cells already on the current path. - Why use a
foundflag instead of returning inside the loop? If a neighbor returnsTrueand we returnedTrueimmediately,board[row][col]would stay overwritten with""in the caller's grid! Savingfound = True, breaking out of the neighbor loop, and runningboard[row][col] = saved_letterright beforereturn foundguarantees a single exit path that cleans up after both hits and dead ends.
from typing import List # Sentinel written into a board cell while it sits on the active DFS path. # Because every character word[index] has length 1 and VISITED has length 0, # a marked cell can never match word[index] (even if word contains "#" or spaces). VISITED = "" # Four orthogonal steps (down, up, right, left) as (row_delta, col_delta) pairs. DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def _match_from( board: List[List[str]], word: str, index: int, row: int, col: int, ) -> bool: """Return True if word[index:] can be formed starting at (row, col) without reusing marked cells.""" # Check bounds strictly (< 0 and >= len) before indexing; negative indices in Python wrap around! if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]): return False # Rejects both wrong letters and cells already on the current path (whose value is VISITED == ""). if board[row][col] != word[index]: return False # Base case: we just matched the final character of word, so a complete valid path exists. if index == len(word) - 1: return True # Mark (row, col) in place so recursive steps cannot step back onto this cell. saved_letter = board[row][col] board[row][col] = VISITED found = False for row_delta, col_delta in DIRECTIONS: next_row = row + row_delta next_col = col + col_delta if _match_from(board, word, index + 1, next_row, next_col): found = True break # Stop exploring remaining directions as soon as one path succeeds # Restore the cell BEFORE returning on both success and failure so the caller's board is untouched. board[row][col] = saved_letter return found- What sentinel value is safe? Every
Add two fast pre-checks in O(L) extra space
Backtracking still runs into trouble on adversarial inputs like a board full of
"a"andword = "aaaaaaaab": every prefix of"a"s matches, so DFS explores countless paths before discovering there is no"b"anywhere on the board. Two quick linear checks rule out impossible words up front:- Length cap: since no cell can be visited twice, any word with
len(word) > rows * colscannot fit on the board. - Letter-count check: count how many times each character appears in
wordusingremaining = Counter(word). As we scanboard, we decrementremaining[letter]ONLY for letters present inremaining. Notice why we countwordrather than building aCounterof the entireboard:remainingstores at mostlen(word)keys, preserving ourO(L)extra-space guarantee even on huge grids with arbitrary characters!
from collections import Counter from typing import List def _has_enough_letters(board: List[List[str]], word: str) -> bool: """Return True if the board has at least as many copies of each letter as word needs.""" # remaining: Counter mapping each distinct needed letter -> count still needed, e.g. {'A': 1, 'B': 2}. # Tracking only letters from word keeps extra memory at O(len(word)) instead of O(rows * cols). remaining = Counter(word) for row in board: for letter in row: if letter in remaining: remaining[letter] -= 1 for needed_count in remaining.values(): if needed_count > 0: return False return True- Length cap: since no cell can be visited twice, any word with
Trace Sample 1 and Sample 2 step by step
Let's trace
word = "TUNNEL"(L = 6, indices0..5) on the3 x 4board from Example 1:Initial board: Active path at index = 4 ('E' at (2,2)): T U N K "" "" "" K R O N P R O "" P M L E P M L "" P(0,0)matchesword[0] = 'T', overwrites(0,0)with"".- Down
(1,0) = 'R'!='U'(returnsFalse). - Up
(-1,0)is out of bounds (returnsFalse). - Right
(0,1) = 'U'matchesword[1], overwrites(0,1)with"".- Down
(1,1) = 'O'fails; up(-1,1)is out of bounds; right(0,2) = 'N'matchesword[2], marks"".- Down
(1,2) = 'N'matchesword[3], marks"".- Down
(2,2) = 'E'matchesword[4], marks""(shown on the right above).- Down
(3,2)is out of bounds. - Up
(1,2)holds"", which fails"" != 'L'— preventing us from stepping backward! - Right
(2,3) = 'P'!='L'. - Left
(2,1) = 'L'matchesword[5](index == 5, the last index) -> returnsTrue!
- Down
- Down
- Down
- Down
- Down
As each recursive call
breaks out of its loop, it executesboard[row][col] = saved_letter, restoring(2,2) -> 'E',(1,2) -> 'N',(0,2) -> 'N',(0,1) -> 'U', and(0,0) -> 'T'.Now compare two
Falsequeries on the same grid: - Forword = "TROT",_has_enough_lettersseesremaining['T'] == 2while the grid holds only one'T', returningFalsebefore starting DFS. - For Example 2 (word = "NONE"),_has_enough_letterspasses because the grid holds two'N's, one'O', and one'E'. During DFS,(1,2) = 'N'steps left to(1,1) = 'O', where stepping back right onto(1,2)sees"" != 'N'and(0,2) = 'N'is unreachable diagonally — so(1,1)and(1,2)restore their letters andexistscleanly returnsFalse.Complete solution
Put
exists,_has_enough_letters, and_match_fromtogether:from collections import Counter from typing import List # Sentinel written into a board cell while it sits on the active DFS path. # Because every character word[index] has length 1 and VISITED has length 0, # a marked cell can never match word[index] (even if word contains "#" or spaces). VISITED = "" # Four orthogonal steps (down, up, right, left) as (row_delta, col_delta) pairs. DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def exists(board: List[List[str]], word: str) -> bool: # Phase 1: Handle trivial word and empty-grid boundaries. if word == "": return True if not board or not board[0]: return False rows = len(board) cols = len(board[0]) # Phase 2: Fast pruning before launching an exponential search. # Since no cell can be visited twice, a path holds at most rows * cols letters. if len(word) > rows * cols: return False if not _has_enough_letters(board, word): return False # Phase 3: Try starting a depth-first path from every cell on the grid. for row in range(rows): for col in range(cols): if _match_from(board, word, 0, row, col): return True return False def _has_enough_letters(board: List[List[str]], word: str) -> bool: """Return True if the board has at least as many copies of each letter as word needs.""" # remaining: Counter mapping each distinct needed letter -> count still needed, e.g. {'A': 1, 'B': 2}. # Tracking only letters from word keeps extra memory at O(len(word)) instead of O(rows * cols). remaining = Counter(word) for row in board: for letter in row: if letter in remaining: remaining[letter] -= 1 for needed_count in remaining.values(): if needed_count > 0: return False return True def _match_from( board: List[List[str]], word: str, index: int, row: int, col: int, ) -> bool: """Return True if word[index:] can be formed starting at (row, col) without reusing marked cells.""" # Check bounds strictly (< 0 and >= len) before indexing; negative indices in Python wrap around! if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]): return False # Rejects both wrong letters and cells already on the current path (whose value is VISITED == ""). if board[row][col] != word[index]: return False # Base case: we just matched the final character of word, so a complete valid path exists. if index == len(word) - 1: return True # Mark (row, col) in place so recursive steps cannot step back onto this cell. saved_letter = board[row][col] board[row][col] = VISITED found = False for row_delta, col_delta in DIRECTIONS: next_row = row + row_delta next_col = col + col_delta if _match_from(board, word, index + 1, next_row, next_col): found = True break # Stop exploring remaining directions as soon as one path succeeds # Restore the cell BEFORE returning on both success and failure so the caller's board is untouched. board[row][col] = saved_letter return found✅ Submit now — all tests should pass.
Intuition & how it works
Imagine solving a word-search puzzle by placing a penny on each square as your finger traces the word one letter at a time. Whenever you reach a dead end — all adjacent squares are off the board, hold the wrong letter, or already have a penny on them — you lift the last penny and try a different neighbor from the previous square. That step-forward-and-undo pattern is called backtracking (building a candidate solution one choice at a time and undoing a choice as soon as it cannot lead to a valid answer).
The naive alternative is to generate every possible non-overlapping path of length L across the grid first and compare each finished string with word. That fails quickly because the number of simple paths grows exponentially (O(3^L) per start square), wasting huge amounts of work extending paths whose very first or second letter was already wrong. Worse, storing a separate rows x cols boolean visited grid allocates O(rows * cols) memory even when word is only 3 or 4 letters long.
Instead, we run a depth-first search (DFS, following one path as deep as matching letters allow before backing up) directly on board and use the cell itself as the penny: while (row, col) is on the active path, we temporarily overwrite board[row][col] with "", then restore its original letter before returning. Watch how this plays out on Example 3, searching for "cct" on a 2 x 2 grid:
Board:
(0,0)='c' (0,1)='c'
(1,0)='t' (1,1)='z'
- Try start
(0,0): matches'c'(index = 0), marks(0,0) = "". Down(1,0) = 't'fails'c', so it moves right to(0,1) = 'c'(index = 1), marking(0,1) = "". From(0,1), down(1,1) = 'z'fails't'and left(0,0) = ""fails't'. Dead end! Both(0,1)and(0,0)restore'c'. - Try start
(0,1): matches'c'(index = 0), marks(0,1) = "". Left(0,0) = 'c'matchesindex = 1, marks(0,0) = "". From(0,0), down(1,0) = 't'matchesindex = 2(the last letter!). Both marked cells restore'c'as the calls unwind, returningTrue.
Complexity
- Time:
O(R * C * 3^L)in the worst case, whereRis the number of rows,Cis the number of columns, andLislen(word). First, our length check and letter-frequency scan inspectword(Lcharacters) andboard(R * Ccells) once inO(R * C + L)time. Then we may start a DFS from each of theR * Cgrid cells. A path ofLcells takesL - 1steps: forL >= 2, the first step tries at most 4 neighbors, and each of the remainingL - 2steps can enter at most 3 unvisited neighbors because the cell we just came from is marked"". Summing across levels givesO(3^L)recursive calls per starting cell. (This bound is tight: on a grid of'a's with two separated'b's, searching for"a" * 10 + "bb"passes the letter-count check and explores every 10-cell path of'a's.) - Space:
O(L)extra memory. Because we mark visited cells in place onboardinstead of allocating aVisited[R][C]matrix, the recursion call stack holds at mostLactive frames (one per matched character ofword), and_has_enough_lettersstores aCounterof only the distinct characters inword(at mostLkeys), neverO(R * C).
Edge cases
- Empty word (
word == ""): returnsTrueimmediately (even on an empty board[]), because zero cells are needed to spell zero characters. - Empty board (
[]or[[]]with non-emptyword): returnsFalsebefore touchingboard[0][0]. - Single-cell board (
[["q"]]):"q"returnsTrue,"p"returnsFalse, and"qq"returnsFalsebecause(0, 0)cannot be used twice. - Word longer than total cells (
len(word) > R * C): pruned immediately inO(1)time, e.g.,"a" * 10on a3 x 3grid. - Full-board snake path (
"a" * 9on a3 x 3grid of"a"): returnsTruevia a winding path that visits all 9 cells once. - Case sensitivity and special characters:
"a"does not match"A", and words containing"#"or spaces still work becauseVISITED = ""has length 0 whereas everyword[index]has length 1. - Board preservation:
boardis guaranteed to equal its original contents whetherexistsreturnsTrueorFalse.
Common mistakes
- Returning
Truebefore restoringboard[row][col]: writingif _match_from(...): return Trueinside the loop leaves""scattered across the caller'sboardwhenever a word is found. Always storefound = True,break, restoreboard[row][col] = saved_letter, and only then return. - Using a printable character like
"#"as the visited marker: if an input test searches for"A#B"on a board containing"#", a marked cell falsely matches'#'! Using""(empty string) cannot collide with any single characterword[index]. - Forgetting Python's negative-index wraparound: omitting
row < 0orcol < 0letsboard[-1][col]read the bottom row of the grid instead of failing out of bounds, allowing illegal wraparound paths across opposite edges. - Not removing cells from a
visitedset when backtracking: if you use asetinstead of in-place marking and only callvisited.add((r, c))withoutvisited.remove((r, c))on backtrack, one failed branch permanently blocks valid paths that pass through(r, c)from a different direction. - Counting the whole board into a hash map when
O(L)space was requested: buildingCounterover allR * Cboard cells can useO(R * C)memory on arbitrary alphabets; countingword(Counter(word)) and decrementing only matching keys keeps space strictlyO(L).
Alternative approaches
- Separate
rows x colsbooleanvisitedmatrix: sameO(R * C * 3^L)time,O(R * C + L)space. Prefer this in multi-threaded servers whereboardis shared across threads read-only, or when rows are immutable strings (List[str]). - Search from the rarer endpoint of
word: ifword[-1]appears fewer times onboardthanword[0], reversingwordsearches the exact same undirected grid paths in reverse while starting from fewer candidate cells and failing earlier on heavily skewed grids (such as"aaaaab").
Follow-up questions
- How can we track the active path directly inside board without allocating a separate visited array, and what time and space bounds result? Before exploring neighbors of
(row, col), savesaved_letter = board[row][col]in a local variable on the call stack and setboard[row][col] = "". Because everyword[index]has length 1, any step back onto(row, col)sees"" != word[index]and returnsFalseimmediately; once neighbor calls finish, setboard[row][col] = saved_letterto restore the grid. Worst-case time remainsO(R * C * 3^L)(4 choices on step 1, at most 3 unvisited choices on the remainingL - 2steps from each ofR * Cstart cells), while extra space drops fromO(R * C + L)toO(L)for the recursion stack andwordcounter. - How would your approach change if we had to search for thousands of target words across the same grid? Insert all target words into a trie (a prefix tree where words sharing a starting prefix share the same path of nodes from the root) and run a single DFS from each board cell that walks the grid and the trie simultaneously. Shared prefixes like
"cat","catch", and"category"are traced once instead of three separate times, and once a word is found you can prune empty leaf branches from the trie so later starts skip them. - What changes in both code and worst-case runtime if diagonal neighbor steps are also permitted? Expand
DIRECTIONSfrom 4 offsets to all 8 horizontal, vertical, and diagonal offsets. The first step from a start cell then branches at most 8 ways and every subsequent step branches at most 7 ways (excluding the cell we just came from), increasing worst-case time toO(R * C * 7^L)while keeping extra space atO(L). - How can you prevent stack-overflow errors in Python when the grid and target word contain thousands of characters? Replace recursion with an explicit stack of state frames
[row, col, index, next_dir_idx]. Pushing a frame saves and marksboard[row][col] = ""; each iteration advancesnext_dir_idx(0..3) to push the next matching neighbor, and whennext_dir_idx == 4(or when cleaning up after finding the end ofword), popping a frame restoresboard[row][col]inO(L)heap memory without touching Python's ~1,000-frame call-stack cap.
Follow-up questions
- How can we track the active path directly inside board without allocating a separate visited array, and what time and space bounds result?
- How would your approach change if we had to search for thousands of target words across the same grid?
- What changes in both code and worst-case runtime if diagonal neighbor steps are also permitted?
- How can you prevent stack-overflow errors in Python when the grid and target word contain thousands of characters?
Similar questions
- XGBoost vs. LightGBM for Conversion Prediction
- Vehicle Trip Reservation API and Inventory Model
- Marketplace Booking Conversion Drivers
- Near-Zero-Downtime Relational Database Major Upgrade
- Cluster HTTP Request Routing and Resilient Retries
- 2D Max Pooling with Source Coordinates