Skip to main content

Number of Islands II - Solution & Explanation

HardPremiumFree on FleetCodeArrayHash TableUnion Find14 min readAsked at: Amazon, Meta, Uber +7
Practice this problem

Problem Statement

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] = [ri, ci] is the position (ri, ci) at which we should operate the ith operation.

Return an array of integers answer where answer[i] is the number of islands after turning the cell (ri, ci) 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 <= 104
  • 1 <= m * n <= 104
  • positions[i].length == 2
  • 0 <= ri < m
  • 0 <= ci < n

 

Follow up: Could you solve it in time complexity O(k log(mn)), where k == positions.length?

Approach Overview

Problem Overview: You start with an empty m x n water grid. Land positions are added one by one. After each addition, return the current number of islands. The challenge is updating the island count efficiently as the grid evolves.

Approach 1: Recompute Islands with DFS/BFS (O(k * m * n) time, O(m * n) space)

After every land addition, rebuild the entire island count by scanning the grid and running DFS or BFS from each unvisited land cell. This uses a standard flood-fill traversal across the grid stored in an array. The approach is simple but extremely expensive because you reprocess the whole grid for each operation. With k additions, the complexity becomes O(k * m * n), which quickly times out for large grids.

Approach 2: Incremental BFS Merge (O(k * m * n) worst-case time, O(m * n) space)

Instead of recomputing everything, treat each new land cell as a new island and then check its four neighbors. If neighboring cells already belong to islands, run a traversal to merge connected components. A hash table or grid structure tracks visited cells and island IDs. This avoids scanning the entire grid each time, but merges can still trigger large traversals. In dense grids, repeated BFS/DFS merges degrade back to near O(k * m * n).

Approach 3: Union-Find (Disjoint Set Union) (O(k α(mn)) time, O(m * n) space)

Union-Find models the grid as a set of disjoint components. Each cell maps to a unique index. When you add land, initialize a new set and increase the island count. Check the four neighboring cells; if any neighbor is already land, union their sets. If two previously separate components merge, decrement the island count. Path compression and union by rank make operations nearly constant time, giving an overall complexity of O(k α(mn)), where α is the inverse Ackermann function. This approach relies on the Union Find data structure to efficiently maintain connected components as the grid updates.

Recommended for interviews: Union-Find is the expected solution. Interviewers want to see that you recognize the dynamic connectivity pattern and model islands as disjoint sets. Explaining the brute-force DFS approach first shows baseline understanding, but implementing Union-Find demonstrates strong algorithmic skill and familiarity with near-constant-time connectivity operations.

Solution

We use a two-dimensional array grid to represent a map, where 0 and 1 represent water and land respectively. Initially, all cells in grid are water cells (i.e., all cells are 0), and we use a variable cnt to record the number of islands. The connectivity between islands can be maintained by a union-find set uf.

Next, we traverse each position (i, j) in the array positions. If grid[i][j] is 1, it means that this position is already land, and we directly add cnt to the answer; otherwise, we change the value of grid[i][j] to 1, and increase the value of cnt by 1. Then, we traverse the four directions of up, down, left, and right of this position. If a certain direction is 1, and this position does not belong to the same connected component as (i, j), then we merge this position with (i, j), and decrease the value of cnt by 1. After traversing the four directions of up, down, left, and right of this position, we add cnt to the answer.

The time complexity is O(k times \alpha(m times n)) or O(k times log(m times n)), where k is the length of positions, and \alpha is the inverse function of the Ackermann function. In this problem, \alpha(m times n) can be considered as a very small constant.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recompute with DFS/BFSO(k * m * n)O(m * n)Conceptual baseline or very small grids
Incremental BFS MergeO(k * m * n) worst caseO(m * n)When experimenting with dynamic merges without DSU
Union-Find (Disjoint Set)O(k α(mn))O(m * n)Optimal solution for dynamic connectivity problems

Video Solution

Leetcode 305 Number of Islands IIRen Zhang7,476 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Number of Islands II easy or hard?
Number of Islands II is categorized as a Hard problem on LeetCode. The difficulty comes from recognizing that the grid changes dynamically and that recomputing islands each time is too slow. Efficiently solving it requires understanding and implementing Union-Find.
Number of Islands II Python/Java solution
Most solutions implement a Union-Find class with path compression and union by rank. The grid index is usually flattened using index = row * n + col. Python, Java, C++, Go, and TypeScript implementations all follow the same pattern: add land, check four neighbors, union sets, and update the island count.
How to solve Number of Islands II in O(n)?
Treat the problem as dynamic connectivity. Maintain a Union-Find structure for all grid cells. Each time land is added, create a new set and union it with any adjacent land cells. Because Union-Find operations are nearly constant time with path compression, the overall complexity becomes O(k α(mn)), which behaves close to linear in practice.
What is the best approach for Number of Islands II?
The optimal approach uses Union-Find (Disjoint Set Union). Each grid cell is treated as a node, and when land is added you union it with neighboring land cells. Path compression and union by rank make each operation nearly constant time, giving overall complexity of O(k α(mn)), where k is the number of land additions.
Is Number of Islands II asked at Google/Amazon/Meta?
Dynamic connectivity and Union-Find problems frequently appear in interviews at companies like Google, Amazon, and Meta. Number of Islands II specifically tests whether you recognize when to use a disjoint set structure instead of repeatedly running DFS or BFS.
What data structure is used in Number of Islands II?
The key data structure is Union-Find (Disjoint Set Union). It tracks connected components efficiently and supports fast union and find operations. Arrays map each grid cell to a parent node, while rank or size heuristics keep the structure balanced.
What is the time complexity of Number of Islands II?
Using Union-Find, the time complexity is O(k α(mn)), where k is the number of operations and α is the inverse Ackermann function, which grows extremely slowly. Space complexity is O(m * n) to store parent and rank arrays for the grid.

Ready to solve this problem?

Practice Number of Islands II with our built-in code editor and test cases.

Practice on FleetCode