Interview conceptCoding & Algorithms

Number Of Islands, Grid BFS/DFS And Backtracking

Asked of: Software Engineer

Last updated

What's being tested

These problems test grid traversal as graph search: modeling cells as vertices, using four-directional adjacency, and finding connected components with BFS or DFS. They also probe backtracking with visited-state restoration, boundary safety, and the ability to justify correctness and O(mn)O(mn) or bounded-search complexity.

Patterns & templates

  • Flood fill: scan every cell; on unvisited land, increment islands and call dfs or enqueue it; each cell is processed once, O(mn)O(mn) time.
  • BFS template: use deque, mark cells visited when enqueuing, and explore (row + dr, col + dc) for four direction vectors.
  • DFS template: stop on out-of-bounds, water, or visited cells; mark before recursion to prevent cycles and duplicate work.
  • In-place visitation: mutate land to water when allowed; otherwise maintain a boolean matrix, trading input preservation for O(mn)O(mn) auxiliary space.
  • Perimeter counting: each land cell contributes four edges; subtract one for every adjacent land neighbor, or count water/out-of-grid sides directly.
  • Backtracking search: mark a cell, recurse to the next character, then unmark on return; reject immediately on bounds, mismatch, or reuse.
  • API rectangle search: recursively split inclusive rectangles, prune empty regions using the presence query, and track the strict call budget carefully.

Common pitfalls

Pitfall: Marking a cell after exploring it allows cycles and duplicate queue entries; mark it when discovered, not when removed.

Pitfall: Confusing four-directional connectivity with diagonals, or mixing inclusive rectangle bounds with half-open indexing.

Pitfall: Forgetting to restore visited[row][col] during backtracking causes one failed path to corrupt all later paths.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts