Skip to content

Interview Solver

FeaturesPricingHelp
Sign In
FeaturesPricingHelpSign In
  1. Interview Questions
  2. /
  3. Problems
  4. /
  5. 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.

Solve it in your browserRead the solution
EasyArrayDepth-First SearchBreadth-First SearchMatrixAsked at 106 companies incl. Google, Amazon, Meta

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

1
2
3
4

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.

Start Free Trial

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

  1. Let old = image[sr][sc]. If old == color, return the image as is.
  2. Recolor the start and push it on a stack.
  3. Pop a pixel; for each of its four neighbors that is in bounds and still old, recolor it and push it.
  4. 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)

ApproachTimeSpace
Repeated sweepsO((m · n)²)O(1)
Recursive DFSO(m · n)O(m · n) call stack
Iterative DFS with an explicit stackO(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 image
▸Flood 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

  • Number of IslandsMediumFlood fill (DFS/BFS on a grid)
  • Rotting OrangesMediumMulti-source BFS
  • Word SearchMediumGrid backtracking (DFS)
  • Accounts MergeMediumUnion-find over shared keys

Get live help in the real interview

Working solutions in real time during your actual interview. Invisible to screensharing.

Start Free Trial

No credit card required

Interview Solver
  • Home
  • About
  • Pricing
  • Sign in
  • Contact
  • Blog
  • Companion
  • Mobile
  • Help Center
  • Developers
  • Use Cases
  • AI Interview Copilot
  • Coding Interview Copilot
  • AI Interview Assistant
  • Software Engineer
  • Product Manager
  • Misc
  • Privacy Policy
  • Terms and Conditions
  • Refund & Cancellation
  • Discord Community
  • Affiliate Program
  • Compare
  • All Comparisons
  • vs Final Round AI
  • vs UltraCode
  • vs Interview Coder
  • vs LockedIn AI
  • vs AI Apply
  • Free Tools
  • ATS Resume Checker
  • STAR Method Builder
  • Salary Lookup
  • Big O Cheat Sheet
  • Total Comp Calculator
  • View All →
  • Interview Questions
  • Google Questions
  • Amazon Questions
  • Microsoft Questions
  • Meta Questions
  • Apple Questions
  • TikTok Questions
  • View All →
© 2026 Interview Solver, Inc. All rights reserved.