Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
You are given an empty 2D binary grid grid
of size mxn
. The grid represents a map where 0
's represent water and 1
's represent land. Initially, all the cells of grid
are water cells (ie, 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] = [r i , c i ]
is the position (r i , c i )
at which we should operate the i th
operation.
Return an array of integers answer
where answer[i]
is the number of islands after turning the cell (r i , c i )
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 <= 10 4
1 <= m * n <= 10 4
positions[i].length == 2
0 <= r i < m
0 <= c i < n
Follow up: Could you solve it in time complexity O(k log(mn))
, where k == positions.length
?
Python
# time complexity: O(m*n) # space complexity: O(m*n) from typing import List class Solution: class UnionFind: def __init__(self, size): self.rep = [i for i in range(size )] self.rank = [0] * size self.count = 0 def find(self, node): if node != self.rep[node]: self.rep[node] = self.find(self.rep[ node]) return self.rep[node] def union(self, node1, node2): rep1 = self.find(node1) rep2 = self.find(node2) if rep1 != rep2: if self.rank[rep1] > self.rank[rep2]: self.rep[rep2] = rep1 elif self.rank[rep2] < self.rank[rep1]: self.rep[rep1] = rep2 else: self.rep[rep2] = rep1 self. rank[rep1] += 1 self.count -= 1 def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: uf = self.UnionFind(m * n) res = [] land_map = set() for row, col in positions: if (row, col) in land_map: res.append(uf.count) continue land_map.add((row, col)) uf.count += 1 for i, j in [(-1, 0), (1, 0), (0, 1), (0, -1)]: r, c = row + i, col + j if r < 0 or c < 0 or r >= m or c >= n: continue if (r, c) in land_map: uf.union(row * n + col, r * n + c) res.append(uf.count) return res m = 3 n = 3 positions = [[0, 0], [0, 1], [1, 2], [2, 1]] print(Solution().numIslands2(m, n, positions))