DSA Tracker

Easy

Flood Fill (Recursion)

An easy Recursion problem included in Apna College. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Recursion
Sheets
1
Core for
11 roles
Platform
LeetCode

The problem

Given a 2D grid and a starting cell, fill all connected cells of the same color with a new color, starting from the given cell.

Example 1

Input
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output
[[2,2,2],[2,2,0],[2,0,1]]
Why
The starting cell and all 4-directionally connected 1s are replaced with 2.

Example 2

Input
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
Output
[[2,2,2],[2,2,2]]

Constraints

  • 1 <= image.length, image[i].length <= 50
  • 0 <= image[i][j], newColor <= 65535

How to think about it

Updated 2026-09-09

The grid is an implicit graph where matching adjacent colors define edges. Changing the color of a cell naturally marks it as visited, eliminating the need for an external visited set—provided the target replacement color is actually different from the start.

Approaches, worst first

  1. Depth-first search recursion

    time O(m * n) · space O(m * n)

    Record initial color, overwrite current cell with newColor, and recurse into all four orthogonal neighbors matching the initial color. Fits within call stack limits due to small grid bounds.

  2. Breadth-first search queueWrite this one

    time O(m * n) · space O(m * n)

    Enqueue starting coordinate, then dequeue and recolor neighbors level by level. Prevents deep recursion call stack consumption at the cost of heap allocation.

Where people lose marks · 2
  • Infinite recursion when newColor equals the starting cell's original color. Because the cell value never changes, recursion re-visits the same cell indefinitely unless early-exited.
  • Checking neighbor validity after recursing rather than before, leading to out-of-bounds matrix indices.

The theory behind it

Recursion — the ground this problem stands on. All Recursion problems

What Recursion is

Recursion is a nesting doll that opens to reveal an identical smaller doll inside. In programming, a function solves a substantial problem by delegating smaller versions of the exact same question to fresh invocations of itself. Each invocation operates on shrunken input until hitting an irreducible foundation called a base case, which returns an immediate answer and permits the waiting cascade to resolve backwards.

When to reach for it

Reach for recursion when a problem possesses self-similar subproblems, such as traversing branched tree structures, exploring graph pathways, or generating combinations. Phrases asking for all permutations, subset generation, exhaustive maze navigation, or hierarchical file system traversals signal recursive decomposition. It is natural whenever the answer to a large instance depends on assembling identical solutions for smaller subsets.

How the pattern works

Structure every recursive method around two mandatory stages: the termination stop and the shrinking recurrence. Write the base condition first so the function exits before attempting further execution. Next, trust the recursive call to return valid answers for smaller inputs without mentally unwinding every level at once. Pass accumulation state forward through parameters, or combine child return values on the ascent phase once deeper calls return.

What each operation costs

OperationTime
call stack memory allocation per frameO(d)
traversal of branching recursive call treeO(b^d)
single branch linear recursive unwindO(n)
What usually goes wrong with Recursion
  • Omitting a base case or writing a condition that input values leap over without triggering, triggering fatal call stack overflow crashes.
  • Modifying shared mutable containers across sibling branches without undoing edits on backtracking steps, contaminating alternative search paths.
  • Recomputing duplicate subproblems inside branching calls without memoizing past returns, causing execution times to explode exponentially.

Which roles need this problem

Recursion is a core topic for these 11 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 5 more roles, including SDE / Backend Engineer, Full-Stack Developer, Security Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Recursion problems

Problem set and role mapping as of .