Uber · Question 73 · Backtracking
Word Search II
Problem
Given a 2D board and a list of words, return all words found in the board. Each word must be constructed from adjacent letters without reusing a cell.
Approach
Use a Trie for word lookup + backtracking DFS for exploring the board.
Time O(m×n×4^L)Space O(total word chars + recursion)
How it works
- 1Index all words in a Trie.
- 2DFS the board following Trie edges only.
- 3Collect words at terminal nodes; prune to avoid repeats.
Sample input / output
Input: 4 4 oaan etae ihkr iflv 4 oath pea eat rain Output: ['eat', 'oath']
Constraints
m == board.length; 1 <= m, n <= 12; 1 <= words.length <= 3*10^4; lowercase only.
Solution — read it, then walk it
Time O(m×n×4^L)Space O(total word chars + recursion)Loops 5Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/46
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