Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonFacebookGoogleBloomberg

Word Search

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Steps
setup

Initialize board dimensions and directions

The algorithm calculates the number of rows and columns in the board and sets up the directions array for exploring neighbors (down, up, right, left).

💡 Knowing the board size and directions upfront allows the DFS to navigate the grid systematically.
Line:rows, cols = len(board), len(board[0]) directions = [(1,0), (-1,0), (0,1), (0,-1)]
💡 The directions array encodes all possible moves from any cell, enabling concise neighbor exploration.
📊
Word Search - Watch the Algorithm Execute, Step by Step
Watching the algorithm step through each recursive call and backtrack reveals how the search space is pruned and how the word is matched incrementally, which is difficult to grasp from code alone.
Step 1/20
·Active fillAnswer cell
enteringboard="[['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]"word="ABCCED"
Call Path (current → root)
exist(board, word)
choosingi=0j=0index=0
Call Path (current → root)
exist(board, word)
Remaining
(0,0)
enteringr=0c=0index=0
Call Path (current → root)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A]
choosingr=0c=0index=0
Call Path (current → root)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A]
pruningr=1c=0index=1
Call Path (current → root)
dfs(1,0,1)
dfs(0,0,0)
exist(board, word)
Partial: [A]
board[1][0] = 'S' != 'B'
pruningr=-1c=0index=1
Call Path (current → root)
dfs(-1,0,1)
dfs(0,0,0)
exist(board, word)
Partial: [A]
out of bounds
enteringr=0c=1index=1
Call Path (current → root)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B]
choosingr=0c=1index=1
Call Path (current → root)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B]
pruningr=1c=1index=2
Call Path (current → root)
dfs(1,1,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B]
board[1][1] = 'F' != 'C'
pruningr=-1c=1index=2
Call Path (current → root)
dfs(-1,1,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B]
out of bounds
enteringr=0c=2index=2
Call Path (current → root)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C]
choosingr=0c=2index=2
Call Path (current → root)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C]
enteringr=1c=2index=3
Call Path (current → root)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C, C]
choosingr=1c=2index=3
Call Path (current → root)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C, C]
enteringr=2c=2index=4
Call Path (current → root)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C, C, E]
choosingr=2c=2index=4
Call Path (current → root)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Remaining
downuprightleft
Partial: [A, B, C, C, E]
pruningr=3c=2index=5
Call Path (current → root)
dfs(3,2,5)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B, C, C, E]
out of bounds
pruningr=1c=2index=5
Call Path (current → root)
dfs(1,2,5)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B, C, C, E]
visited cell
pruningr=2c=3index=5
Call Path (current → root)
dfs(2,3,5)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B, C, C, E]
board[2][3] = 'E' != 'D'
backtrackingr=2c=1index=5
Call Path (current → root)
dfs(2,1,5)
dfs(2,2,4)
dfs(1,2,3)
dfs(0,2,2)
dfs(0,1,1)
dfs(0,0,0)
exist(board, word)
Partial: [A, B, C, C, E, D]
Found 1: [ABCCED]

Key Takeaways

Backtracking explores all possible paths but prunes early when mismatches or boundaries occur.

This pruning is hard to see in code but clear when watching the recursion tree unfold.

In-place marking of visited cells avoids extra memory and prevents cycles effectively.

Understanding this technique is easier when you see cells change state during recursion.

The recursion tree shows how the algorithm tries neighbors in order and backtracks upon failure.

Seeing the order of exploration clarifies why some paths are abandoned and others succeed.

Practice

(1/5)
1. Consider the following Python code implementing the bitmask backtracking solution for N-Queens II. What is the final return value of totalNQueens(4)?
easy
A. 2
B. 0
C. 1
D. 4

Solution

  1. Step 1: Trace initial call for n=4

    Start with row=0, no columns or diagonals occupied, all 4 columns available.
  2. Step 2: Count valid placements recursively

    Backtracking explores all valid queen placements; for n=4, there are exactly 2 distinct solutions.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Known result for 4-queens is 2 solutions [OK]
Hint: 4-queens has 2 solutions; bitmask backtracking counts all [OK]
Common Mistakes:
  • Off-by-one counting
  • Confusing number of solutions with board size
2. You need to partition a string into substrings such that every substring is a palindrome. Which algorithmic approach guarantees finding all possible palindrome partitions efficiently by pruning invalid partitions early?
easy
A. Backtracking that explores all substring partitions and checks palindrome validity dynamically
B. Dynamic programming that counts the number of palindromic substrings without generating partitions
C. Greedy approach that picks the longest palindrome substring at each step
D. Breadth-first search that generates partitions level by level without palindrome checks

Solution

  1. Step 1: Understand problem requirements

    The problem requires generating all palindrome partitions, not just counting or finding one.
  2. Step 2: Identify suitable algorithm

    Backtracking explores all partitions and prunes invalid ones by checking palindrome substrings dynamically, ensuring completeness and correctness.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Backtracking with palindrome checks finds all partitions [OK]
Hint: Backtracking explores all partitions with palindrome pruning [OK]
Common Mistakes:
  • Assuming greedy longest palindrome picks all partitions
  • Confusing counting palindromes with generating partitions
  • Ignoring palindrome checks in BFS
3. You are given a partially filled 9x9 grid where each row, column, and 3x3 sub-box must contain digits 1 through 9 without repetition. Which algorithmic approach guarantees finding a valid solution if one exists?
easy
A. Greedy algorithm that fills cells with the first valid digit found
B. Breadth-first search exploring all possible digit placements simultaneously
C. Dynamic programming by storing subproblems of partially filled grids
D. Backtracking with constraint propagation and heuristic ordering of empty cells

Solution

  1. Step 1: Understand problem constraints

    The problem requires filling cells respecting row, column, and box constraints, which is a classic constraint satisfaction problem.
  2. Step 2: Identify algorithm that guarantees solution

    Backtracking with constraint propagation prunes invalid choices early, and heuristic ordering reduces branching, ensuring completeness and efficiency.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Constraint propagation + heuristic ordering is standard for Sudoku solvers [OK]
Hint: Constraint satisfaction problems need backtracking with pruning [OK]
Common Mistakes:
  • Assuming greedy or BFS alone can solve Sudoku efficiently
4. What is the time complexity of the optimal backtracking with Trie approach for Word Search II, given a board of size MxN and a list of words with maximum length L? Assume the Trie is already built.
medium
A. O(M * N * 4 * 3^(L-1)) due to pruning and adjacency constraints
B. O(M * N * 4^L * W), where W is the number of words
C. O(M * N * L^2) because each cell explores all prefixes
D. O(M * N * L) since each cell is visited once per character

Solution

  1. Step 1: Identify branching factor in backtracking

    From each cell, up to 4 directions are possible initially, then up to 3 directions for subsequent steps due to no revisiting.
  2. Step 2: Calculate complexity with pruning

    Trie pruning reduces unnecessary paths, so complexity is roughly O(M * N * 4 * 3^(L-1)) where L is max word length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Matches known complexity from Trie + backtracking analysis [OK]
Hint: Branching factor reduces after first step due to visited constraints [OK]
Common Mistakes:
  • Confusing W (number of words) as multiplicative factor in optimal approach.
5. If the problem changes so that numbers can be reused multiple times in the permutation (i.e., repetition allowed), which modification to the algorithm is correct?
hard
A. Use a greedy approach to pick the smallest available number at each step until length n is reached.
B. Use the same factorial-based approach but do not remove numbers from the list after selection.
C. Modify factorial computations to account for repeated elements and use a multiset permutation formula.
D. Generate all permutations with backtracking and stop when the k-th is found, since factorial indexing no longer applies.

Solution

  1. Step 1: Understand repetition impact

    Allowing reuse breaks the factorial number system assumption because permutations count changes drastically.
  2. Step 2: Identify correct approach

    Backtracking with early stop can generate permutations with repetition and find the k-th one, as direct factorial indexing is invalid.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Factorial indexing fails with repetition; backtracking is correct fallback [OK]
Hint: Factorial indexing requires unique elements; repetition breaks it [OK]
Common Mistakes:
  • Trying to reuse factorial indexing without adjustment
  • Ignoring repetition changes permutation count
  • Assuming greedy works for k-th permutation with repetition