Two-colour a board with walls and fixed cells
I was asked this
No reports yet. Sign in to say where you were asked it.
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
Noneat 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 + colup 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
Noneon 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
