medium Word Search
Problem Statement
Given an m x n grid of characters board and a string word, return true if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
-
Input: word="ABCCED", board:
{ 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } -
Output: true
-
Explanation: The word exists in the board:
-> { 'A', 'B', 'C', 'E' },
-> { 'S', 'F', 'C', 'S' },
-> { 'A', 'D', 'E', 'E' }
Example 2:
-
Input: word="SEE", board:
{ 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } -
Output: true
-
Explanation: The word exists in the board:
-> { 'A', 'B', 'C', 'E' },
-> { 'S', 'F', 'C', 'S' },
-> { 'A', 'D', 'E', 'E' }
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Try it yourself
Try solving this question here:
🎯 STRICT STANDOUT — Word Search — problem
1. Why / judgment
Exist path in board spelling word, 4-dir, no cell reuse in one path. DFS/backtrack from each start matching word[0]; mark visited; recurse; unmark. Trie optimization for many words (II).
2. Big-O derivation (K11)
O(mn * 3^L) rough (L word len) with careful branching. Space O(L) recursion.
3. Pattern + when-NOT (K12)
Name: GRID DFS BACKTRACK
Recognition: word exists as path in letter grid.
When-NOT: Many words => Word Search II trie. Count paths => different. Diagonal moves if allowed change degree.
4. Edge hand-run (K13)
ABCCED true classic; SEE true; ABFB false typical.
5. Interviewer follow-ups (model answers)
Q1. Why unmark?
A: Cell free for other branches / other starts.
Q2. Prune?
A: Early letter mismatch; optional freq precheck.
Q3. Visited structure?
A: Mutate board temporarily or set.
6. Short drills
Drill A: path for SEE.
Drill B: reuse cell fail.
Drill C: Word Search II pointer.
✅ Solution Word Search
Problem Statement
Given an m x n grid of characters board and a string word, return true if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
-
Input: word="ABCCED", board:
{ 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } -
Output: true
-
Explanation: The word exists in the board:
-> { 'A', 'B', 'C', 'E' },
-> { 'S', 'F', 'C', 'S' },
-> { 'A', 'D', 'E', 'E' }
Example 2:
-
Input: word="SEE", board:
{ 'A', 'B', 'C', 'E' }, { 'S', 'F', 'C', 'S' }, { 'A', 'D', 'E', 'E' } -
Output: true
-
Explanation: The word exists in the board:
-> { 'A', 'B', 'C', 'E' },
-> { 'S', 'F', 'C', 'S' },
-> { 'A', 'D', 'E', 'E' }
Constraints:
m == board.lengthn = board[i].length1 <= m, n <= 61 <= word.length <= 15boardandwordconsists of only lowercase and uppercase English letters.
Solution
The basic approach to solving the word search problem using backtracking is to start at the first character of the word and check all 4 adjacent cells in the grid to see if any of them match the next character of the word. If a match is found, mark the cell as visited and recursively check the next character of the word in the adjacent cells of the newly visited cell. If the entire word is found, return true. If no match is found, backtrack to the previous cell and try a different path. Repeat this process until the entire grid has been searched or the word is found.
Code
This function takes a 2D list board and a string word as input, and returns True if the word can be found in board and False otherwise. It uses a helper function dfs which takes 4 additional parameters: i and j are the current coordinates of the cell that is being visited, k is the index of the current character of the word being matched, and board and word are the inputs passed to the main function.
The dfs function uses a helper variable tmp to store the current value of the cell before it is marked as visited. This is done so that we can backtrack later. It then uses recursion to check if the next character of the word exists in the 4 adjacent cells, and it will mark the cell as visited and move to next index of the word by incrementing k by 1. If the next character is found, the function returns true, if not it backtracks to the previous cell, and continues the search in different path. If the entire word is found, the function returns True, otherwise it returns False after searching the entire grid.
public class Solution {
public static boolean dfs(char[][] board, String word, int i, int j, int k) {
// check if current coordinates are out of grid or the current cell doesn't
// match the current character of the word
if (
i < 0 ||
i >= board.length ||
j < 0 ||
j >= board[0].length ||
board[i][j] != word.charAt(k)
) {
return false;
}
// check if we have reached the end of the word
if (k == word.length() - 1) {
return true;
}
// mark the current cell as visited by replacing it with '/'
char tmp = board[i][j];
board[i][j] = '/';
// check all 4 adjacent cells recursively
boolean res =
dfs(board, word, i + 1, j, k + 1) ||
dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) ||
dfs(board, word, i, j - 1, k + 1);
// backtrack by replacing the current cell with its original value
board[i][j] = tmp;
return res;
}
public boolean exist(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
// start the search from every cell
if (dfs(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test Case 1
char[][] board1 = {
{ 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' },
};
String word1 = "ABCCED";
System.out.println(sol.exist(board1, word1)); // expected output: true
// Test Case 2
char[][] board2 = {
{ 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' },
};
String word2 = "SEE";
System.out.println(sol.exist(board2, word2)); // expected output: true
// Test Case 3
char[][] board3 = {
{ 'A', 'B', 'C', 'E' },
{ 'S', 'F', 'C', 'S' },
{ 'A', 'D', 'E', 'E' },
};
String word3 = "ABCB";
System.out.println(sol.exist(board3, word3)); // expected output: false
char[][] board4 = { { 'a', 'a' } };
String word4 = "aaa";
System.out.println(sol.exist(board4, word4)); // expected output: false
char[][] board5 = { { 'a' } };
String word5 = "a";
System.out.println(sol.exist(board5, word5)); // expected output: true
char[][] board6 = {
{ 'a', 'b', 'c', 'd', 'e' },
{ 'f', 'g', 'h', 'i', 'j' },
{ 'k', 'l', 'm', 'n', 'o' },
{ 'p', 'q', 'r', 's', 't' },
{ 'u', 'v', 'w', 'x', 'y' },
{ 'z', 'a', 'b', 'c', 'd' },
};
String word6 = "abcde";
System.out.println(sol.exist(board6, word6)); // expected output: true
char[][] board7 = {
{ 'a', 'b', 'c', 'd', 'e' },
{ 'f', 'g', 'h', 'i', 'j' },
{ 'k', 'l', 'm', 'n', 'o' },
{ 'p', 'q', 'r', 's', 't' },
{ 'u', 'v', 'w', 'x', 'y' },
{ 'z', 'a', 'b', 'c', 'd' },
};
String word7 = "zabcd";
System.out.println(sol.exist(board7, word7)); // expected output: true
}
}
Time Complexity
The overall time complexity of the algorithm is
: Number of cells in the board. : Each cell can lead to up to 4 recursive calls (one for each direction: up, down, left, right). For a word of length (L), there are up to : possible paths to explore.
Thus, for each cell, the DFS can potentially explore
Space Complexity
The space complexity of the exist function is
🎯 STRICT STANDOUT — Solution Word Search
0. Pattern family
Family: Grid DFS / backtracking with mark-unmark
1. Why / judgment (K3)
Find whether a word exists as a path of adjacent cells (4-dir) without reuse. This is classic choose/explore/un-choose: mark cell visited, recurse four neighbors, unmark on return so other paths can reuse it. Why not BFS? We need exact letter sequence and path-local visited — DFS stack carries the path state naturally.
2. Worked complexity / derivation (K11)
m×n board, word length L.
Worst: try every start cell O(mn), each DFS explores up to 4^L branches but pruned by letters and visited → still O(mn·4^L) worst-case bound.
Space O(L) recursion + visited (in-place mark is O(1) extra beyond stack).
Not O(mn) — exponential in L unless heavy pruning.
3. Pattern + recognition + when-NOT (K12)
Name: GRID WORD SEARCH (DFS backtrack + visit restore)
Recognition: 2D board + find contiguous word path without reusing cell; letters given.
When-NOT: Find all words from dictionary → Trie+DFS (Word Search II). Allow reuse cells → different. Subsequence not path-adjacent → not this.
4. Edge hand-run (K13)
board=[[A,B],[C,D]] word="ABDC" path A-B-D-C works if edges allow.
word="" → true by convention / early.
single cell match/mismatch; word longer than mn → false.
Revisit trap: without unmark, second branch fails wrongly.
5. Interviewer follow-ups & drills
Q1. Why unmark?
Model answer: Visited is path-local; another route may need that cell.
Q2. Diagonal?
Model answer: Usually 4-dir only — confirm problem statement.
Q3. Word Search II change?
Model answer: Prebuild Trie of words; share DFS prefix — not one word DFS each.
Recognize it: Enumerate all subsets / permutations / combinations under constraints → recurse, choose, un-choose.
▶ Visualize this problem (step it, predict each fork)
🤖 Don't fully get this? Learn it with Claude
Stuck on Word Search? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Word Search** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Word Search** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Word Search**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Word Search**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.