> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Number of Islands II Python Solution

> Tested Python solution for LeetCode 305 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 305, [Hard](/catalog/hard). Topics: [Union Find](/catalog/topics/union-find), [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table). [View on LeetCode](https://leetcode.com/problems/number-of-islands-ii/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 305   # by problem number
lcpy gen -s number_of_islands_ii   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0305.Number%20of%20Islands%20II/images/tmp-grid.jpg)

```
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.
```

```
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 <= ri < m`
* `0 <= ci < n`

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_islands_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/number_of_islands_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class UnionFind:
    def __init__(self, n: int) -> None:
        self.p = list(range(n))
        self.size = [1] * n

    def find(self, x: int) -> int:
        if self.p[x] != x:
            self.p[x] = self.find(self.p[x])
        return self.p[x]

    def union(self, a: int, b: int) -> bool:
        pa, pb = self.find(a), self.find(b)
        if pa == pb:
            return False
        if self.size[pa] > self.size[pb]:
            self.p[pb] = pa
            self.size[pa] += self.size[pb]
        else:
            self.p[pa] = pb
            self.size[pb] += self.size[pa]
        return True


class Solution:
    # Time: O(k * alpha(m * n)) — one union-find pass over positions
    # Space: O(m * n) — parent and size arrays
    def num_islands2(self, m: int, n: int, positions: list[list[int]]) -> list[int]:
        uf = UnionFind(m * n)
        land = set()
        count = 0
        answer: list[int] = []
        for i, j in positions:
            if (i, j) in land:
                answer.append(count)
                continue
            land.add((i, j))
            count += 1
            for x, y in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
                if (x, y) in land and uf.union(i * n + j, x * n + y):
                    count -= 1
            answer.append(count)
        return answer
```

## Complexity

| Time | Space |
| - | - |
| O(k \* alpha(m \* n)) — one union-find pass over positions | O(m \* n) — parent and size arrays |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.