PPractick

DSA interview question

Flood Fill

Medium · Data structures · Topics: graph, dfs, bfs, matrix

The problem

A paint program's bucket tool recolours a region: starting from the clicked pixel, every pixel connected to it 4-directionally with the same original colour gets the new colour. It's a traversal (BFS or DFS) from the start pixel that only moves into neighbours with the original colour. One subtle case: if the new colour equals the original, nothing should change, and a naive implementation would loop forever, because recoloured pixels would still match.

Example: image [[1,1,1], [1,1,0], [1,0,1]], start (1, 1), colour 2 → [[2,2,2], [2,2,0], [2,0,1]].

Function signature

vector<vector<int>> floodFill(vector<vector<int>> image, int sr, int sc, int color);

Test cases

Input (image, sr, sc, color)OutputExplanation
([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2)[[2,2,2],[2,2,0],[2,0,1]]The bottom-right 1 touches only diagonally
([[0,0,0],[0,1,0]], 1, 1, 2)[[0,0,0],[0,2,0]]A single-pixel region
([[1,2],[2,1]], 0, 0, 3)[[3,2],[2,1]]Diagonals don't count
([[0,0,0],[0,0,0]], 0, 0, 0)[[0,0,0],[0,0,0]]Same colour: unchanged
([[5]], 0, 0, 7)[[7]]

(Confirm: connectivity is 4-directional; only pixels of the starting pixel's original colour are recoloured.)

How interviewers phrase it

Clarifying questions to ask

  1. 4-directional or 8-directional? (4.)
  2. Return a new image or modify in place? (Either; a copy is returned here.)
  3. What if the new colour equals the old one? (Nothing changes.)

Follow-ups to expect

  1. "Why is the same-colour case special?"
  2. "BFS or DFS?"
  3. "Why do you not need a visited array?"
  4. "Where else is this pattern used?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in