KatInterview

305. Number of Islands II

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to count the number of islands after a series of addLand operations on an initially water-filled grid. An island is a group of horizontally or vertically connected land cells. Since we are adding land cells one by one and need to track the connectivity and count of islands, this problem involves dynamically managing connected components. A naive approach of running a full grid scan (like BFS or DFS) after each addLand operation would be too slow, with a complexity of O(k * m * n), where k is the number of operations. A more efficient data structure is needed to handle the merging of components. The Union-Find (or Disjoint Set Union - DSU) data structure is perfectly suited for this task.

Solution

Number of Islands II in Python

class Solution:
    def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
        # Initialize DSU structure. -1 represents water.
        parent = [-1] * (m * n)
        rank = [0] * (m * n)
        count = 0
        result = []

        # Find operation with path compression
        def find(i):
            if parent[i] != i:
                parent[i] = find(parent[i])
            return parent[i]

        # Union operation with union by rank
        def union(i, j):
            nonlocal count
            root_i = find(i)
            root_j = find(j)
            if root_i != root_j:
                if rank[root_i] > rank[root_j]:
                    parent[root_j] = root_i
                elif rank[root_i] < rank[root_j]:
                    parent[root_i] = root_j
                else:
                    parent[root_j] = root_i
                    rank[root_i] += 1
                count -= 1 # Two islands have merged
        
        # Directions for neighbors (right, left, down, up)
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

        for r, c in positions:
            idx = r * n + c

            # If the cell is already land, the number of islands doesn't change.
            if parent[idx] != -1:
                result.append(count)
                continue

            # Turn water into a new island
            parent[idx] = idx
            rank[idx] = 1
            count += 1

            # Check neighbors to see if we can merge islands
            for dr, dc in directions:
                nr, nc = r + dr, c + dc
                neighbor_idx = nr * n + nc

                # Check if neighbor is within bounds and is land
                if 0 <= nr < m and 0 <= nc < n and parent[neighbor_idx] != -1:
                    union(idx, neighbor_idx)
            
            result.append(count)
            
        return result

Number of Islands II in Java

class Solution {
    private int[] parent;
    private int[] rank;
    private int count;

    // Find operation with path compression
    private int find(int i) {
        if (parent[i] == i) {
            return i;
        }
        parent[i] = find(parent[i]);
        return parent[i];
    }

    // Union operation with union by rank
    private void union(int i, int j) {
        int root_i = find(i);
        int root_j = find(j);
        if (root_i != root_j) {
            if (rank[root_i] > rank[root_j]) {
                parent[root_j] = root_i;
            } else if (rank[root_i] < rank[root_j]) {
                parent[root_i] = root_j;
            } else {
                parent[root_j] = root_i;
                rank[root_i]++;
            }
            count--; // Two islands have merged
        }
    }

    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        // Initialize DSU structure. -1 represents water.
        parent = new int[m * n];
        java.util.Arrays.fill(parent, -1);
        rank = new int[m * n];
        count = 0;
        List<Integer> result = new ArrayList<>();
        
        // Directions for neighbors (right, left, down, up)
        int[] dr = {0, 0, 1, -1};
        int[] dc = {1, -1, 0, 0};
        
        for (int[] pos : positions) {
            int r = pos[0];
            int c = pos[1];
            int id = r * n + c;
            
            // If the cell is already land, the number of islands doesn't change.
            if (parent[id] != -1) {
                result.add(count);
                continue;
            }
            
            // Turn water into a new island
            parent[id] = id;
            rank[id] = 1;
            count++;
            
            // Check neighbors to see if we can merge islands
            for (int i = 0; i < 4; i++) {
                int nr = r + dr[i];
                int nc = c + dc[i];
                int neighborId = nr * n + nc;
                
                // Check if neighbor is within bounds and is land
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && parent[neighborId] != -1) {
                    union(id, neighborId);
                }
            }
            
            result.add(count);
        }
        
        return result;
    }
}

Number of Islands II in C++

class Solution {
private:
    vector<int> parent;
    vector<int> rank;
    int count;

    // Find operation with path compression
    int find(int i) {
        if (parent[i] == i) {
            return i;
        }
        return parent[i] = find(parent[i]);
    }

    // Union operation with union by rank
    void unite(int i, int j) {
        int root_i = find(i);
        int root_j = find(j);
        if (root_i != root_j) {
            if (rank[root_i] > rank[root_j]) {
                parent[root_j] = root_i;
            } else if (rank[root_i] < rank[root_j]) {
                parent[root_i] = root_j;
            } else {
                parent[root_j] = root_i;
                rank[root_i]++;
            }
            count--; // Two islands have merged
        }
    }

public:
    vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
        // Initialize DSU structure. -1 represents water.
        parent.assign(m * n, -1);
        rank.assign(m * n, 0);
        count = 0;
        vector<int> result;
        
        // Directions for neighbors (right, left, down, up)
        int dr[] = {0, 0, 1, -1};
        int dc[] = {1, -1, 0, 0};
        
        for (const auto& pos : positions) {
            int r = pos[0];
            int c = pos[1];
            int id = r * n + c;
            
            // If the cell is already land, the number of islands doesn't change.
            if (parent[id] != -1) {
                result.push_back(count);
                continue;
            }
            
            // Turn water into a new island
            parent[id] = id;
            rank[id] = 1;
            count++;
            
            // Check neighbors to see if we can merge islands
            for (int i = 0; i < 4; ++i) {
                int nr = r + dr[i];
                int nc = c + dc[i];
                int neighbor_id = nr * n + nc;
                
                // Check if neighbor is within bounds and is land
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && parent[neighbor_id] != -1) {
                    unite(id, neighbor_id);
                }
            }
            
            result.push_back(count);
        }
        
        return result;
    }
};

Number of Islands II in TypeScript

function numIslands2(m: number, n: number, positions: number[][]): number[] {
    // Initialize DSU structure. -1 represents water.
    const parent: number[] = new Array(m * n).fill(-1);
    const rank: number[] = new Array(m * n).fill(0);
    let count = 0;
    const result: number[] = [];

    // Find operation with path compression
    const find = (i: number): number => {
        if (parent[i] === i) {
            return i;
        }
        parent[i] = find(parent[i]);
        return parent[i];
    };

    // Union operation with union by rank
    const unite = (i: number, j: number): void => {
        const rootI = find(i);
        const rootJ = find(j);
        if (rootI !== rootJ) {
            if (rank[rootI] > rank[rootJ]) {
                parent[rootJ] = rootI;
            } else if (rank[rootI] < rank[rootJ]) {
                parent[rootI] = rootJ;
            } else {
                parent[rootJ] = rootI;
                rank[rootI]++;
            }
            count--; // Two islands have merged
        }
    };

    // Directions for neighbors (right, left, down, up)
    const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]];

    for (const pos of positions) {
        const r = pos[0];
        const c = pos[1];
        const id = r * n + c;

        // If the cell is already land, the number of islands doesn't change.
        if (parent[id] !== -1) {
            result.push(count);
            continue;
        }

        // Turn water into a new island
        parent[id] = id;
        rank[id] = 1;
        count++;

        // Check neighbors to see if we can merge islands
        for (const dir of directions) {
            const nr = r + dir[0];
            const nc = c + dir[1];
            const neighborId = nr * n + nc;

            // Check if neighbor is within bounds and is land
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && parent[neighborId] !== -1) {
                unite(id, neighborId);
            }
        }

        result.push(count);
    }

    return result;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.