- Interview Questions
- /
- Problems
- /
- Flood Fill
Flood Fill
Recolor the connected region of same-colored pixels that contains a starting pixel, like a paint bucket tool. A basic grid DFS/BFS, with one edge case that loops forever if you miss it. Solve it below in Python or JavaScript, then read the walkthrough.
Problem
You're given an image as a 2D grid of integers image, where each value is a pixel's color. You're also given a starting pixel (sr, sc) and a new color.
Perform a "paint bucket" fill: the starting pixel, and every pixel connected to it through a chain of up, down, left or right neighbors that all share the starting pixel's original color, should be changed to color. Diagonal neighbors do not count as connected.
Return the image after the fill.
Example 1
- Input
- image = [[2, 2, 0], [2, 0, 1], [2, 2, 1]], sr = 0, sc = 0, color = 5
- Output
- [[5, 5, 0], [5, 0, 1], [5, 5, 1]]
Every 2 is reachable from the top-left corner through other 2s. The 0s and 1s are a different color, so they stop the fill.
Example 2
- Input
- image = [[1, 0], [0, 1]], sr = 0, sc = 0, color = 4
- Output
- [[4, 0], [0, 1]]
The bottom-right 1 only touches the start diagonally, so it is not filled.
Example 3
- Input
- image = [[3, 3], [3, 0]], sr = 0, sc = 0, color = 3
- Output
- [[3, 3], [3, 0]]
The new color matches the old one, so nothing changes.
Constraints
- 1 ≤ m, n ≤ 50, where image is m × n
- 0 ≤ image[i][j], color < 2¹⁶
- 0 ≤ sr < m and 0 ≤ sc < n
Practice
Runs 12 tests in your browser. Python loads on the first run (about 6 MB, then cached). Press ⌘/Ctrl + Enter to run.
Get asked Flood Fill in a real interview?
Interview Solver gives you a working solution live, during your actual coding interview. Invisible to screensharing.
How to solve Flood Fill
Pattern: Grid DFS/BFS over a connected component
The grid is a graph: each pixel is a node, and it has an edge to each of its four neighbors that share its color. The fill is "find the connected component containing the start and recolor it", which is exactly what a depth-first or breadth-first search does.
You don't even need a separate visited set. Recoloring a pixel as soon as you reach it marks it as done, since it no longer has the original color and the search won't enter it again.
That trick has one hole: if color equals the original color, recoloring changes nothing, so every pixel still looks unvisited and the search loops forever. Check for that case first and return the image unchanged.
Approach 1: Repeated sweeps
Recolor the start pixel, then sweep the whole grid repeatedly, recoloring any original-colored pixel next to a recolored one, until a sweep changes nothing. Correct, but a winding region can need one sweep per pixel.
Time O((m · n)²) · Space O(1)
Approach 2: Recursive DFS
Recolor the current pixel, then recurse into each in-bounds neighbor with the original color. Short and the most common answer, but the recursion can go as deep as the region is large, which in Python can hit the default recursion limit on a 50 × 50 grid.
Time O(m · n) · Space O(m · n) call stack
Approach 3: Iterative DFS with an explicit stack
- Let
old = image[sr][sc]. Ifold == color, return the image as is. - Recolor the start and push it on a stack.
- Pop a pixel; for each of its four neighbors that is in bounds and still
old, recolor it and push it. - When the stack is empty, return the image.
Recoloring on push means each pixel is pushed at most once.
Time O(m · n) · Space O(m · n)
| Approach | Time | Space |
|---|---|---|
| Repeated sweeps | O((m · n)²) | O(1) |
| Recursive DFS | O(m · n) | O(m · n) call stack |
| Iterative DFS with an explicit stack | O(m · n) | O(m · n) |
Solution code
Try the practice editor first. Both solutions pass every test above.
Flood Fill solution in Python
def flood_fill(image: list[list[int]], sr: int, sc: int, color: int) -> list[list[int]]:
old = image[sr][sc]
if old == color:
return image # nothing to change, and recoloring would not mark visits
rows, cols = len(image), len(image[0])
image[sr][sc] = color
stack = [(sr, sc)]
while stack:
r, c = stack.pop()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and image[nr][nc] == old:
image[nr][nc] = color
stack.append((nr, nc))
return imageFlood Fill solution in JavaScript
function floodFill(image, sr, sc, color) {
const old = image[sr][sc];
if (old === color) return image; // nothing to change, and recoloring would not mark visits
const rows = image.length;
const cols = image[0].length;
image[sr][sc] = color;
const stack = [[sr, sc]];
while (stack.length) {
const [r, c] = stack.pop();
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] === old) {
image[nr][nc] = color;
stack.push([nr, nc]);
}
}
}
return image;
}Common mistakes
- Not handling color == original color, which makes the search revisit the same pixels forever.
- Including diagonal neighbors. Only up, down, left and right count.
- Comparing neighbors to the new color or to the current pixel instead of the original color of the start pixel.
- Checking bounds after indexing. In Python, a negative index silently wraps to the other side of the grid.
- Recursing on a large region in Python and hitting the recursion limit.
What interviewers look for
Name the graph view in one line: "pixels are nodes, same-colored neighbors are edges, and I'm recoloring one connected component." Then mention the same-color edge case before you write any code; interviewers often wait to see whether you catch it.
Say why you don't need a visited set (recoloring marks pixels), and mention the recursion depth if you write the recursive version. Offering the explicit stack as the safe alternative is usually enough.
Follow-up questions
How would you count the number of separate regions of each color?
Loop over every pixel and start a fill from each one that has not been visited, counting one region per fill. That is the Number of Islands pattern, O(m · n) overall.
What if diagonal neighbors also counted as connected?
Use eight directions instead of four. Nothing else changes.
How do real paint programs fill huge images quickly?
They use a scanline fill: from a pixel, fill the whole horizontal run of matching color in one go, then push one seed per run in the rows above and below. It touches each pixel about once with far fewer stack operations than per-pixel DFS.
Companies that ask Flood Fill
Flood Fill is tagged by 106 companies in our interview dataset. The score shows how often it comes up at each company.
- Cerebras Systems100%
- Caci International95%
- Ericsson92%
- Buffer92%
- Clever91%
- Arrow Electronics89%
- Tokyo Electron88%
- Ansys87%
- Criteo84.6%
- Smarthr82%
- Mozilla82%
- Sas Software81%
- Apptio81%
- Checkr80%
- Zimmer Biomet76%
- Bear Robotics75%
- Culture Amp73%
- Gainsight73%
- Plaid73%
- Knowbe473%
- Cloud Software Group73%
- Omnicell73%
- Revature72%
- D Matrix72%
and 82 more.
Practice next
Get live help in the real interview
Working solutions in real time during your actual interview. Invisible to screensharing.
Start Free TrialNo credit card required