Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

305. Number of Islands II

Explanation

To solve this problem, we can use the Union-Find (Disjoint Set Union) data structure. We will iterate through the positions where lands are added, and for each land, we check the neighboring positions to see if they are also lands. If they are, we union these lands. We maintain a count of the number of islands after each land is added.

Algorithm:

  1. Initialize a Union-Find data structure to keep track of islands.
  2. Iterate through the positions where lands are added.
  3. For each land position:
    • Increment the island count by 1.
    • Mark the land position as visited.
    • Check the neighboring positions (up, down, left, right).
    • If a neighboring position is also a land:
      • Union the current land with the neighboring land.
      • Decrement the island count by 1.
  4. Add the island count to the result list.

Time Complexity:

  • The time complexity for this approach is O(k * α(m*n)), where k is the number of operations, m and n are the dimensions of the grid, and α is the inverse Ackermann function (almost constant).

Space Complexity:

  • The space complexity is O(m*n) to store the Union-Find data structure.
class Solution {
    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        List<Integer> result = new ArrayList<>();
        UnionFind uf = new UnionFind(m, n);
        
        for (int[] pos : positions) {
            int r = pos[0];
            int c = pos[1];
            int p = r * n + c;
            uf.addLand(p);
            
            if (r > 0 && uf.isValid((r - 1) * n + c)) uf.union(p, (r - 1) * n + c);
            if (r < m - 1 && uf.isValid((r + 1) * n + c)) uf.union(p, (r + 1) * n + c);
            if (c > 0 && uf.isValid(r * n + c - 1)) uf.union(p, r * n + c - 1);
            if (c < n - 1 && uf.isValid(r * n + c + 1)) uf.union(p, r * n + c + 1);
            
            result.add(uf.getCount());
        }
        
        return result;
    }
    
    class UnionFind {
        int[] parent;
        int[] rank;
        int count;
        
        public UnionFind(int m, int n) {
            parent = new int[m * n];
            rank = new int[m * n];
            count = 0;
        }
        
        public void addLand(int p) {
            parent[p] = p;
            rank[p] = 0;
            count++;
        }
        
        public int find(int p) {
            if (parent[p] != p) {
                parent[p] = find(parent[p]);
            }
            return parent[p];
        }
        
        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP != rootQ) {
                if (rank[rootP] > rank[rootQ]) {
                    parent[rootQ] = rootP;
                } else if (rank[rootP] < rank[rootQ]) {
                    parent[rootP] = rootQ;
                } else {
                    parent[rootQ] = rootP;
                    rank[rootP]++;
                }
                count--;
            }
        }
        
        public int getCount() {
            return count;
        }
        
        public boolean isValid(int p) {
            return parent[p] != -1;
        }
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.