Number of Islands II Problem
Description
LeetCode Problem 305.
You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0's represent water and 1's represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0's).
We may perform an add land operation which turns the water at position into a land. You are given an array positions where positions[i] = [r_i, c_i] is the position (r_i, c_i) at which we should operate the i^th operation.
Return an array of integers answer where answer[i] is the number of islands after turning the cell (r_i, c_i) into a land.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:

Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1,1,2,3]
Explanation:
Initially, the 2d grid is filled with water.
- Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land. We have 1 island.
- Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land. We still have 1 island.
- Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land. We have 2 islands.
- Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land. We have 3 islands.
Example 2:
Input: m = 1, n = 1, positions = [[0,0]]
Output: [1]
Constraints:
1 <= m, n, positions.length <= 10^41 <= m * n <= 10^4positions[i].length == 20 <= r_i < m0 <= c_i < n
Follow up: Could you solve it in time complexity O(k log(mn)), where k == positions.length?
Solution
Approach: Union-Find
Running a fresh DFS over the whole grid after every operation costs O(mn) per step. Instead we keep the islands in a union-find (disjoint set) structure and update the count as each cell turns into land.
Give every cell the id r * n + c. Keep a counter count of islands. For each position:
- If the cell is already land, nothing changes: record
countagain. Positions can repeat, and forgetting this case counts the same cell as a new island. - Otherwise mark it as land and add one island, since a new land cell on its own is an island.
- Look at its four neighbors. For each neighbor that is land, find the roots of both cells. If the roots differ, the new cell connects two separate islands: union them and subtract one from
count. If they are equal, the two cells are already on the same island (for example, two neighbors that were joined earlier), so the count stays the same.
Then record count. Comparing roots before merging matters: a new cell touching the same island from two sides must only subtract once.
find uses path halving, so the trees stay flat and each operation takes almost constant time.
Complexity: O(mn + k·α(mn)) time, where k is the number of positions and α is the inverse Ackermann function (at most 4 or 5 in practice), and O(mn) extra space for the parent array and the land flags.
class Solution:
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
parent = list(range(m * n)) # union-find over cells, cell id = r * n + c
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
land = [False] * (m * n)
count = 0
answer = []
for r, c in positions:
cell = r * n + c
if not land[cell]: # adding land to a cell that is already land changes nothing
land[cell] = True
count += 1
for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if 0 <= nr < m and 0 <= nc < n and land[nr * n + nc]:
a, b = find(cell), find(nr * n + nc)
if a != b: # two islands become one
parent[a] = b
count -= 1
answer.append(count)
return answer