Count Islands After Land Additions
UberSoftware Engineer · OnsiteLast updated
This question tests the ability to manage connected components in a grid dynamically, specifically requiring an efficient approach to track changes after incremental land additions.
Problem Statement
You are given an n x n grid initially filled with water (0). You are provided with a sequence of k operations, where each operation is represented as a list of coordinates [row, col]. For each operation, you transform the cell at (row, col) from water to land (1). After each addition, return the current number of connected components of land (islands) in the grid.
Two pieces of land are connected if they are adjacent horizontally or vertically.
Function Signature
def countIslandsAfterAdditions(n: int, positions: List[List[int]]) -> List[int]:
Constraints
1 <= n <= 10001 <= len(positions) <= n * n- Coordinates are 0-indexed.
Examples
Example 1:
Input: n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]
- After [0,0]: Grid has 1 island.
- After [0,1]: New land connects to [0,0]. Grid has 1 island.
- After [1,2]: New land is isolated. Grid has 2 islands.
- After [2,1]: New land connects to [1,2] (via vertical/horizontal neighbors). Grid has 2 islands.
Output:
[1, 1, 2, 2]
Edge Cases
- Multiple additions to the same coordinate (the cell remains land).
- Adding land that merges two or more existing islands.
- An empty
positionslist or a full grid.
Hints
Hint 1
A brute-force approach would involve running BFS or DFS after every addition, which is inefficient. Consider using the Disjoint Set Union (DSU) data structure.
Hint 2
Map each 2D grid coordinate `(r, c)` to a 1D index `r * n + c` to simplify the DSU operations.
Hint 3
When adding a new piece of land, increment the total island count and check its four neighbors; for each neighbor that is already land, union the sets and decrement the island count if a merge occurs.
Follow-up questions
- What is the time complexity of your DSU approach in terms of n and the number of operations?
- How would you modify your solution if land could be removed (changed from 1 to 0) as well?
- If the grid size `n` was extremely large (e.g., 10^9), how would you handle the memory constraints?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.