← Questions
Count islands with diagonal connectivity
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Apr 2026. It tests grids, dfs and union-find.
Given a grid of 1s (land) and 0s (water), count the islands, where two land cells belong to the same island when they touch in any of the eight directions: horizontally, vertically or diagonally.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
count_islands_8(grid: list[list[int]]) -> int— the grid is rectangular and may be empty. An empty grid or a grid with no land returns0.
Example
count_islands_8([[1,0],
[0,1]]) -> 1 # the two cells touch diagonally
count_islands_8([[1,0,0],
[0,0,1],
[1,0,0]]) -> 3 # no two land cells are within one row and one column
count_islands_8([[1,1,0,0],
[0,0,0,1],
[0,1,0,1]]) -> 3
Constraints
-
0 <= rows, columns <= 1000androws * columns <= 10^6.
Clarifying questions
- Are diagonal neighbours connected? (Yes here, unlike the classic four-direction version.)
- May I modify the grid to mark visited cells?
- Can the grid be empty or jagged?
What a strong answer covers
- A flood fill (BFS or iterative DFS) from each unvisited land cell over its eight neighbours, counting each start.
O(rows * columns)time. - Marking a cell when it is pushed, not when it is popped, so it is never queued twice.
- Avoiding recursion: a grid of one huge island would overflow the call stack.
- Union-find as an alternative, useful for the follow-ups.
- Tests: empty grid, all water, all land, a diagonal chain, single row.
Follow-ups
- Land is added one cell at a time; report the island count after each addition (union-find).
- Return the size of the largest island.
- The grid is too big for memory and arrives row by row: count islands with only two rows in memory.
Where it's asked
- Google · Onsite coding · Last asked Apr 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
grids · dfs · union-find
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
