Word Search in Grid Using Backtracking in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to find a word in a grid grows as the grid and word get bigger.
How does the search time change when the grid size or word length increases?
Analyze the time complexity of the following code snippet.
function exist(board, word) {
const rows = board.length;
const cols = board[0].length;
function backtrack(r, c, index) {
if (index === word.length) return true;
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[index]) return false;
const temp = board[r][c];
board[r][c] = '#';
const found = backtrack(r+1, c, index+1) || backtrack(r-1, c, index+1) || backtrack(r, c+1, index+1) || backtrack(r, c-1, index+1);
board[r][c] = temp;
return found;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (backtrack(i, j, 0)) return true;
}
}
return false;
}
This code tries to find a given word in a 2D grid by exploring all possible paths using backtracking.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive backtracking calls exploring up to 4 directions for each letter in the word.
- How many times: For each cell in the grid (rows * cols), the backtracking explores up to 4 choices per letter in the word (word length = k).
As the grid size and word length grow, the number of paths to check grows very fast because each letter can lead to 4 new directions.
| Input Size (n = rows*cols) | Word Length (k) | Approx. Operations |
|---|---|---|
| 10 | 3 | About 10 * 4^3 = 640 |
| 100 | 5 | About 100 * 4^5 = 10,2400 |
| 1000 | 7 | About 1000 * 4^7 = 16,384,000 |
Pattern observation: The operations grow exponentially with the word length and linearly with the grid size.
Time Complexity: O(n * 4^k)
This means the time grows linearly with the number of cells and exponentially with the length of the word, because each letter can lead to 4 new paths.
[X] Wrong: "The search time is just proportional to the grid size because we only check each cell once."
[OK] Correct: Actually, the search explores many paths from each cell, especially for longer words, so the time grows much faster than just the grid size.
Understanding this complexity helps you explain why backtracking can be slow and shows your grasp of recursive search patterns, a useful skill in many coding challenges.
"What if we limited the search directions to only right and down? How would the time complexity change?"
Practice
Solution
Step 1: Understand backtracking in word search
Backtracking tries all possible paths in the grid to find the target word by exploring neighbors recursively.Step 2: Eliminate other options
Sorting, counting words, or replacing characters are not related to backtracking's purpose in this problem.Final Answer:
To explore all possible paths to find the word -> Option CQuick Check:
Backtracking = Explore paths [OK]
- Thinking backtracking sorts or modifies the grid
- Confusing backtracking with simple searching
- Assuming backtracking counts words directly
Solution
Step 1: Understand grid indexing
Grid rows and columns start at 0 and go up to length - 1, so valid indices satisfy 0 <= row < length.Step 2: Check each option
if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length) correctly uses >= 0 and < length. Others use > 0 or <= length, which are incorrect for zero-based indexing.Final Answer:
if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length) -> Option BQuick Check:
Check boundaries with >=0 and < length [OK]
- Using > 0 excludes first row/column
- Using <= length allows out-of-bound index
- Confusing inclusive and exclusive bounds
"CAT" in the given grid?const grid = [
['C', 'A', 'T'],
['A', 'T', 'C'],
['T', 'C', 'A']
];
function exist(board, word) {
const rows = board.length;
const cols = board[0].length;
const visited = Array.from({ length: rows }, () => Array(cols).fill(false));
function backtrack(r, c, index) {
if (index === word.length) return true;
if (r < 0 || c < 0 || r >= rows || c >= cols) return false;
if (visited[r][c] || board[r][c] !== word[index]) return false;
visited[r][c] = true;
const res = backtrack(r + 1, c, index + 1) || backtrack(r - 1, c, index + 1) || backtrack(r, c + 1, index + 1) || backtrack(r, c - 1, index + 1);
visited[r][c] = false;
return res;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (backtrack(i, j, 0)) return true;
}
}
return false;
}
console.log(exist(grid, "CAT"));Solution
Step 1: Trace the backtracking search for "CAT"
The word "CAT" can be found starting at grid[0][0] = 'C', then right to 'A', then right to 'T'. The function returns true.Step 2: Confirm no errors and correct return
The code correctly marks visited cells and explores neighbors. It returns true when the word is found.Final Answer:
true -> Option AQuick Check:
Word "CAT" found in grid = true [OK]
- Ignoring visited array causing infinite loops
- Not checking all directions
- Assuming word must be in a straight line only
function backtrack(r, c, index) {
if (index === word.length) return true;
if (r < 0 || c < 0 || r >= rows || c >= cols) return false;
if (board[r][c] !== word[index]) return false;
visited[r][c] = true;
const res = backtrack(r + 1, c, index + 1) || backtrack(r - 1, c, index + 1) || backtrack(r, c + 1, index + 1) || backtrack(r, c - 1, index + 1);
return res;
}Solution
Step 1: Identify missing backtracking step
The function marks visited[r][c] = true but never resets it to false after recursion, causing wrong results.Step 2: Fix by unmarking visited after recursion
Adding visited[r][c] = false after recursive calls allows other paths to use this cell again.Final Answer:
Add visited[r][c] = false after recursive calls to unmark -> Option DQuick Check:
Unmark visited after recursion to backtrack [OK]
- Forgetting to unmark visited cells
- Removing boundary checks causing errors
- Changing base case incorrectly
Solution
Step 1: Understand inefficiency of separate searches
Running backtracking for each word separately repeats many searches, wasting time.Step 2: Use Trie to optimize search
Building a Trie of all words allows backtracking once, pruning paths that don't match any prefix, improving efficiency.Final Answer:
Use a Trie (prefix tree) to reduce repeated searches and backtrack once -> Option AQuick Check:
Trie + backtracking = efficient multi-word search [OK]
- Searching each word independently causing slow performance
- Sorting grid or words doesn't help search
- Modifying grid letters breaks correctness
Ready to prove it?
Pass the test and this pattern moves unknown
