Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Repaint a region of an image

Easy · Target 10 minutes · Graphs · Type asked atAmazonGoogle

An image is a grid of integers, each a pixel colour. Given a starting pixel (sr, sc) and a new color, repaint the starting pixel and every pixel connected to it that has the same original colour. Two pixels are connected if they share a side (up, down, left or right), directly or through a chain of such pixels. Return the image.

Examples

InputOutputWhy
image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2[[2,2,2],[2,2,0],[2,0,1]]The bottom-right 1 touches the region only diagonally, so it keeps its colour.
image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0[[0,0,0],[0,0,0]]The new colour equals the old one: nothing changes.
image = [[1,2,1],[2,1,2],[1,2,1]], sr = 1, sc = 1, color = 7[[1,2,1],[2,7,2],[1,2,1]]The centre has no side neighbour of its colour.

Constraints

  • 1 ≤ rows, cols ≤ 50
  • 0 ≤ image[r][c], color < 2¹⁶
  • 0 ≤ sr < rows, 0 ≤ sc < cols

Hints

Hint 1

Record the original colour of (sr, sc) before changing anything.

Hint 2

A recursive fill(r, c) returns at once if the cell is outside the image or not the original colour; otherwise it repaints the cell and calls itself on the four neighbours.

Hint 3

If the new colour equals the original colour, return the image unchanged. Otherwise repainted cells still look unvisited and the recursion never ends.

Where people lose marks

  • Not handling color equal to the original colour: infinite recursion.
  • Reading image[r][c] before checking that (r, c) is inside the image.
  • Treating diagonal pixels as connected.
  • Comparing with the colour of the current pixel instead of the saved original colour, after the current one has already been repainted.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.