AlgoInsight

DSA problem

Number of Islands II

HardUnion FindPattern: Union Findtop600AmazonGoogleMicrosoftMetaBloomberg

You are given an empty 2D binary grid of size m x n. The grid represents a map where 0s represent water and 1s represent land. Initially, all the cells of the grid are water cells (i.e., all the cells are 0s). We may perform an add land operation which turns the water at position positions[i] = [r_i, c_i] into land. Return an array of integers answer where answer[i] is the number of islands after turning the cell (r_i, c_i) into land.

An island is a maximal group of 1s connected horizontally or vertically (4-directional). The challenge is that operations happen online — after every single addition we must report the current island count, and additions can both create new islands and merge several existing ones into one.

Recomputing the island count from scratch after every operation with BFS/DFS would cost O(K * m * n). The Union-Find approach gives us each operation in amortised O(α(m * n)). We treat each cell index r * n + c as a DSU node. Maintain a running counter of the number of islands.

When we add land at (r, c) that was previously water, increment the counter by 1 (a brand-new singleton island). Then, for each of the 4 neighbours that is land, attempt to union it with (r, c); every successful union decrements the counter by 1 (two islands have become one). If the same position is added twice (a duplicate operation), we leave the counter unchanged. The output array logs the counter after each operation.

Examples

Example 1
Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1,1,2,3]
Explanation: After [0,0]: 1 island. After [0,1]: it joins (0,0), still 1 island. After [1,2]: a separate island, 2 total. After [2,1]: another separate island, 3 total.
Example 2
Input: m = 1, n = 1, positions = [[0,0]]
Output: [1]
Explanation: A single cell becomes a single island.
Example 3
Input: m = 3, n = 3, positions = [[0,0],[0,0]]
Output: [1,1]
Explanation: Adding land to an already-land cell is a no-op; the island count is unchanged.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

graphunion-finddsugridonline

Browse all DSA problems