305. Number of Islands II
Hard ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Advanced Graphs
- Time
- O(m*n + k*alpha(m*n)
- Space
- O(m*n)
Standard Solution (C++)
SummaryGiven an m×n grid initially filled with water, process a sequence of land-addition operations and return the number of distinct islands after each operation. Islands are defined as connected groups of land cells sharing an edge.
Approach
- Use a Disjoint Set Union (DSU) structure over all m×n cells, initializing every cell as water (parent = -1).
- For each position added: mark it as land, increment the island count, then check all four neighbors — if a neighbor is already land,
unionthe two components, decrementing the count each time two distinct roots are merged. - Path compression (recursive find with root caching) and union by rank keep each DSU operation in near-O(1) amortized time (inverse-Ackermann).
- Duplicate positions are handled by checking whether the cell is already land before processing.
#include <vector>
using namespace std;
class Solution {
// Union-Find with path compression and union by rank
struct DSU {
vector<int> parent, rank_;
int islands;
DSU(int n) : parent(n, -1), rank_(n, 0), islands(0) {}
// Returns false if cell was already land (duplicate operation)
bool addLand(int id) {
if (parent[id] != -1) return false;
parent[id] = id;
++islands;
return true;
}
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]); // path compression
return parent[x];
}
void unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return; // already same component
// union by rank: attach smaller tree under larger
if (rank_[ra] < rank_[rb]) swap(ra, rb);
parent[rb] = ra;
if (rank_[ra] == rank_[rb]) ++rank_[ra];
--islands;
}
};
public:
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
DSU dsu(m * n);
vector<int> result;
const int dr[] = {-1, 1, 0, 0};
const int dc[] = {0, 0, -1, 1};
for (const auto& pos : positions) {
int r = pos[0], c = pos[1];
int id = r * n + c;
if (!dsu.addLand(id)) {
// Duplicate: island count unchanged
result.push_back(dsu.islands);
continue;
}
// Merge with any adjacent land cells
for (int d = 0; d < 4; ++d) {
int nr = r + dr[d], nc = c + dc[d];
if (nr >= 0 && nr < m && nc >= 0 && nc < n) {
int nid = nr * n + nc;
if (dsu.parent[nid] != -1) // neighbor is land
dsu.unite(id, nid);
}
}
result.push_back(dsu.islands);
}
return result;
}
}; Time O(k * alpha(m*n)) where k = number of positions and alpha is the inverse-Ackermann function (effectively O(k)) Space O(m * n) for the DSU parent and rank arrays
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
// int find(vector<int>& parent, int idx){
// if(parent[idx]==idx){
// return idx;
// }
// return parent[idx]=find(parent, parent[idx]);
// }
// vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
// vector<int> parent(m*n, -1);
// vector<int> rank(m*n, 0);
// vector<int> res;
// int count=0;
// int dx[4]={-1, 1, 0, 0};
// int dy[4]={0, 0, -1, 1};
// for(const auto& p: positions){
// int x=p[0];
// int y=p[1];
// int idx=x*n+y;
// if(parent[idx]!=-1){
// res.push_back(count);
// continue;
// }
// parent[idx]=idx;
// ++count;
// ++rank[idx];
// for(int i=0; i<4; ++i){
// int nx=x+dx[i];
// int ny=y+dy[i];
// int nidx=nx*n+ny;
// if(nx>=0 && nx<m && ny>=0 && ny<n && parent[nidx]!=-1){
// int r1=find(parent, idx);
// int r2=find(parent, nidx);
// if(r1==r2){
// continue;
// }
// if(rank[r1]<rank[r2]){
// parent[r1]=r2;
// }
// else if(rank[r1]>rank[r2]){
// parent[r2]=r1;
// }
// else{
// parent[r1]=r2;
// ++rank[r2];
// }
// --count;
// }
// }
// if(count<0){
// count=0;
// }
// res.push_back(count);
// }
// return res;
// }
struct DSU {
vector<int> parent;
vector<int> rank;
int count;
DSU(int n): parent(n, -1), rank(n, 0), count(0){}
bool addLand(int idx){
if(parent[idx]!=-1){
return false;
}
parent[idx]=idx;
++count;
// ++rank[idx];
return true;
}
int find(int idx){
if(idx!=parent[idx]){
parent[idx]=find(parent[idx]);
}
return parent[idx];
}
void unite(int i, int j){
int r1=find(i);
int r2=find(j);
if(r1!=r2){
if(rank[r1]>rank[r2]){
parent[r2]=r1;
}
else if(rank[r2]>rank[r1]){
parent[r1]=r2;
}
else{
parent[r2]=r1;
++rank[r1];
}
--count;
}
}
};
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
DSU dsu(m*n);
vector<int> res;
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};
for(const auto& p: positions){
int x=p[0];
int y=p[1];
int idx=x*n+y;
if(!dsu.addLand(idx)){
res.push_back(dsu.count);
continue;
}
for(int i=0; i<4; ++i){
int nx=x+dx[i];
int ny=y+dy[i];
int nidx=nx*n+ny;
if(nx>=0 && nx<m && ny>=0 && ny<n && dsu.parent[nidx]!=-1){
dsu.unite(idx, nidx);
}
}
res.push_back(dsu.count);
}
return res;
}
};
// By using path compression and union by rank, the DSU operations (find and unite) run in nearly O(1) time
// Time Complexity: O(m*n + k*alpha(m*n)) where k is the number of positions, m and n are the dimensions of the grid, and alpha is the inverse Ackermann function which is very slow growing and can be considered almost constant in practice.
// Space Complexity: O(m*n) for the DSU data structure to store the parent and rank arrays. Time O(m*n + k*alpha(m*n) Space O(m*n)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.