Uber · Question 60 · Backtracking
Word Search
Problem
Given a 2D grid and a word, check if the word exists in the grid. You may move in 4 directions, but cannot reuse the same cell.
Approach
DFS from each cell: Check character match Mark as visited (e.g., '#' ) Recurse in 4 directions Unmark on backtrack
Time O(m*n*4^L)Space O(L)
How it works
- 1DFS from every cell matching the first letter.
- 2Mark cells visited with '#' and unmark on backtrack.
- 3Full word consumed means found.
Sample input / output
Input: 3 4 ABCE SFCS ADEE ABCCED Output: True
Constraints
m == board.length; 1 <= m, n <= 6; 1 <= word.length <= 15; uppercase letters.
Solution — read it, then walk it
Time O(m*n*4^L)Space O(L)Loops 2Branches 4Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/28
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits