Count Islands After Land Additions
Updated
Problem statement
Start with a rows by cols grid containing only water. Process each position in positions in order by turning that cell into land.
After every addition, return the number of islands. An island is a maximal group of land cells connected vertically or horizontally. Adding a cell that is already land changes nothing but still produces an output.
Function
countIslandsAfterAdditions(rows: int, cols: int, positions: int[][]) → int[]Examples
Example 1
rows = 3cols = 3positions = [[0,0],[0,1],[1,2],[2,1],[1,1]]return = [1,1,2,3,1]The final center cell joins the three existing components into one island.
Example 2
rows = 1cols = 3positions = [[0,1],[0,1],[0,0],[0,2]]return = [1,1,1,1]The repeated addition is a no-op, and both later cells attach to the existing island.
Example 3
rows = 2cols = 2positions = [[0,0],[1,1],[0,1],[1,0]]return = [1,2,1,1]Diagonal cells are separate. Adding either remaining edge-adjacent cell merges them.
Constraints
1 <= rows, cols <= 10001 <= positions.length <= 100000- Every position is
[row, col]with0 <= row < rowsand0 <= col < cols. - Positions may repeat.
More Google Onsite Interview questions
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Count Islands from Streaming RowsAmazon · ONSITE INTERVIEW
- Dynamic Island CountsUber · PHONE SCREENUber interview questions
- Shortest Distance from All BuildingsWaymo · PHONE SCREENWaymo interview questions
- Number of Islands IISpaceX · PHONE SCREENSpaceX interview questions
- Longest Decreasing Matrix Path with Limited RelaxationsDuolingo · ONSITE INTERVIEWDuolingo interview questions
- Making a Large IslandMeta · ONSITE INTERVIEWMeta interview questions
- Sliding PuzzleNVIDIA · PHONE SCREENNVIDIA interview questions
- Explore an Unknown Grid and Find a PathLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Nearest Charging Station on a GridSpotify · ONSITE INTERVIEW
- Minimize CommuteDatabricks · OA · PHONE SCREENDatabricks interview questions