← Questions
Count identical islands in two grids
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in OpenAI's agentic coding (beta) round, last asked Oct 2024. It tests grids, bfs and graphs.
You get two binary grids of the same size. A region is a maximal group of 1 cells joined up, down, left or right. Two regions match when they contain exactly the same cell coordinates, one region in each grid. Return how many regions match.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
count_matching(grid1: list[str], grid2: list[str]) -> int— each grid is a list of strings of'0'and'1'.
Example
grid1 = ["001", "011", "100"]
grid2 = ["001", "011", "101"]
-> 1 # {(0,2),(1,1),(1,2)} grows by (2,2) in grid2, so only the single cell {(2,0)} matches
grid1 = ["110", "000", "011"]
grid2 = ["100", "000", "011"]
-> 1 # the bottom region matches; the top one shrank to one cell
Constraints
- Both grids have the same shape, up to 1000 x 1000.
- Regions use 4-connectivity, not diagonals.
Clarifying questions
- Must the regions match exactly, or does a region of grid1 count when it is only contained in a region of grid2?
- Are the grids always the same size?
- 4-connected or 8-connected?
- Can I modify the input grids?
What a strong answer covers
- Flood fill (BFS or DFS, iterative to avoid recursion limits) over grid1; for each region, check every cell is
1in grid2 and that no cell of the region touches a1in grid2 outside the region, which is what "exactly the same" means. - An equivalent approach: label the regions of both grids; a grid1 region matches when all its cells carry one grid2 label and that grid2 region has the same size.
- O(rows x cols) time and memory.
- Tests where a region in grid2 is larger, smaller, split in two, or merged with a neighbor.
Follow-ups
- Count regions of grid2 that are sub-islands of grid1 (contained, not equal).
- Count distinct region shapes up to translation.
- Grids too big for memory, streamed row by row.
Where it's asked
- OpenAI · Agentic coding (beta) · Last asked Oct 2024An existing codebase and changes too large to write by hand; you work through them with an AI coding agent · An AI coding agent is expected
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
