Count Islands in a Binary Grid
Updated
Problem statement
You are given a rectangular grid. Each cell is either 1 for land or 0 for water. Return the number of islands.
An island is a group of land cells joined up, down, left or right. Grow the group as far as it goes: every land cell that touches it on a side is part of the same island. Cells that touch only at a corner are not joined.
Function
countIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1],[0,0,0,0]]return = 2The three land cells in the upper-left touch each other on their sides, so they form one island. The three land cells on the right also touch on their sides and form a second island. The two groups never touch, so there are two islands.
Example 2
grid = [[0,0,0],[0,0,0]]return = 0The grid contains no land, so it contains no islands.
Example 3
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 5The five land cells touch each other only at their corners. Corner contact does not join cells, so each land cell is its own island. That gives five islands.
Constraints
1 <= grid.length <= 300.1 <= grid[r].length <= 300for every rowr.- All rows have the same length.
- Every cell is either
0or1. - You may change the grid while you work.
More Apple Phone Screen questions
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Pacific Atlantic Water FlowAnduril · PHONE SCREENAnduril interview questions
- Number of IslandsWhatNot · PHONE SCREEN · ONSITE INTERVIEWWhatNot interview questions
- Maximum Damage PatchGecko Robotics · OA · PHONE SCREEN
- Count the IslandsAdobe · PHONE SCREENAdobe interview questions
- Maximum Area of IslandSkydio · PHONE SCREENSkydio interview questions
- Number of IslandsFleetx · ONSITE INTERVIEW
- Number of IslandsIntuit · ONSITE INTERVIEWIntuit interview questions
- Number of Islands with Diagonal ConnectivityGoogle · ONSITE INTERVIEWGoogle interview questions
- Island Count and Maximum AreaOracle · ONSITE INTERVIEWOracle interview questions
- Max Area of IslandGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions