Skip to main content
LeetCode 305, Hard. Topics: Union Find, Array, Hash Table. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

You are given an empty 2D binary grid grid of size m x n. The grid represents a map where 0s represent water and 1s represent land. Initially, all the cells of grid are water cells (i.e., all the cells are 0s). 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

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, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026