← Uber bank

Uber · Question 60 · Backtracking

Word Search

BacktrackingPythoncode⏱ O(m*n*4^L)💾 O(L)
Product-based

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

  1. 1DFS from every cell matching the first letter.
  2. 2Mark cells visited with '#' and unmark on backtrack.
  3. 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.
yesnoyesno↻ repeatyes↻ repeatyesnoSTARTboard, wordm, n = len(board),len(board[0])DEFINE dfs(r, c, idx)if idx == len(word)RETURN Trueif r < 0 or r >= m orc < 0 or c >= n orboard[r][c] !…RETURN Falsetemp = board[r][c]board[r][c] = '#'found = (dfs(r + 1, c, idx+ 1) orboard[r][c] = tempRETURN foundfor i in range(m)for j in range(n)if dfs(i, j, 0)RETURN TrueRETURN FalseDEFINE 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)]word = next(it)print(exist([row[:] for rowin board], word))if __name__ =="__main__"main()END
  • 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