← Questions

Two-colour a board with walls and fixed cells

0
NetflixCoding

A coding interview question asked at Netflix. It tests graph, bfs and bipartite.

You are given an M x N board as a matrix of integers. Each cell is one of:

  • 1: already painted black
  • 0: already painted white
  • 9: empty, still to be painted
  • -1: a wall, which is never painted

Paint every empty cell black or white so that no two cells that share an edge (up, down, left, right) have the same colour. Walls take no colour and don't constrain their neighbours. Pre-painted cells keep their colour.

Implement color_grid(grid) -> list[list[int]] | None. It returns a new, fully painted board, or None if no valid painting exists. If more than one painting works, return any of them.

Constraints: 0 <= M, N <= 1000. Cell values are in {-1, 0, 1, 9}.

Example 1

input:            output:
 1  9  9           1  0  1
 9 -1  9           0 -1  0
 9  9  9           1  0  1

Example 2

input:  [[0, 9, 9, 0]]   -> None

The two white cells are three steps apart, so the cells between them can't alternate. Replace the third cell with a wall ([[0, 9, -1, 0]]) and the answer becomes [[0, 1, -1, 0]].

Then discuss: how many valid paintings exist, and what changes if diagonal neighbours also count as adjacent?

Clarifying questions

  • Is a 0 x 0 board returned as an empty board?
  • Must the input be left unchanged (return a new board)?
  • Do two pre-painted neighbours with the same colour make the answer None at once?

What a strong answer covers

  • Sees that a grid with edge adjacency is bipartite, so within each connected region of non-wall cells the colour is fixed by the parity of row + col up to one choice per region.
  • Finds regions with an iterative BFS (or a parity check per region), and checks every pre-painted cell in a region agrees on that choice; returns None on a conflict (Example 2).
  • Paints regions with no fixed cells either way, and works in O(M * N) without recursion.
  • Tests both examples, a board of walls, a region split by walls, and conflicting fixed cells.

Follow-ups

  • Count the valid paintings: 2 to the number of regions with no fixed cells, or 0.
  • Diagonal neighbours also count: any 2x2 block of non-wall cells is then impossible.
  • Three colours: the problem becomes much harder (NP-hard in general).

Where it's asked

What it tests

graph · bfs · bipartite · grid

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding