← Uber bank

Uber · Question 73 · Backtracking

Word Search II

BacktrackingPythoncode⏱ O(m×n×4^L)💾 O(total word chars + recursion)
Product-based

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

  1. 1Index all words in a Trie.
  2. 2DFS the board following Trie edges only.
  3. 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.
↻ repeat↻ repeatyesnoyesnoyes↻ repeat↻ repeat↻ repeat↻ repeatSTARTCLASS TrieNodeDEFINE __init__(self)self.children = {}self.word = NoneDEFINE buildTrie(words)root = TrieNode()for word in wordsnode = rootfor c in wordnode =node.children.setdefault(c,TrieNode())node.word = wordRETURN rootDEFINE findWords(board,words)m, n = len(board),len(board[0])root = buildTrie(words)res = []DEFINE dfs(r, c, node)DEFINE = board[r][c]if char not innode.childrenRETURNnext_node =node.children[char]if next_node.wordres.append(next_node.word)next_node.word = Noneboard[r][c] = '#'for dr, dc in ((1, 0),(-1, 0), (0, 1), (0,-1))nr, nc = r + dr, c + dcif 0 <= nr < m and 0<= nc < ndfs(nr, nc, next_node)board[r][c] = charfor i in range(m)for j in range(n)dfs(i, j, root)RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))board = [[c for c innext(it)] for _ inrange(m)]k = int(next(it))words = [next(it) for _ inrange(k)]found = findWords([row[:]for row in board], words)print(sorted(found))if __name__ =="__main__"
  • 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