KatInterview

Live Archipelago Counter with Incremental Land Reclamation

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsunion-findgridconnected-components

Last updated

Count 4-connected land regions in a grid, then report the updated region count after each cell is converted from water to land, using incremental connectivity.

Live Archipelago Counter with Incremental Land Reclamation

You are given a map of a sea as a rectangular grid. A cell holding 0 is water and a cell holding 1 is land. Two land cells are part of the same island if you can travel between them by stepping only onto land cells, moving one step up, down, left, or right each time (diagonal steps do not count).

You are also given a list of reclamation orders. Each order is a pair [row, col] naming a cell. Orders are applied one at a time, in the given sequence:

  • If the named cell is water, it becomes land.
  • If the named cell is already land (either originally or from an earlier order), nothing changes.

Your task is to produce a list of island counts:

  1. The first entry is the number of islands in the original grid, before any order is applied.
  2. After each order is processed, append the number of islands currently on the map (even if that order changed nothing).

The returned list therefore has length len(additions) + 1.

The input grid and the list of orders must not be modified.

Constraints

  • The grid has at least one row and at least one column.
  • All rows have the same length, and the grid has at most 200,000 cells in total.
  • 0 <= len(additions) <= 200,000.
  • Each order consists of two integers that identify a valid cell in the grid.
  • Aim for roughly O(R*C + A*alpha(R*C)) time and O(R*C) extra space, where R*C is the number of cells and A is the number of orders.

Examples

Example 1

Input: count_islands_over_time([[1, 0, 0], [0, 0, 1]], [[0, 1], [1, 1], [1, 1]])

Output: [2, 2, 1, 1]

Example 2

Input: count_islands_over_time([[0, 0]], [[0, 0], [0, 1]])

Output: [0, 1, 1]

Hints

Hint 1

Recomputing the island count from scratch after every order costs O(R*C) each time, which is far too slow at the largest sizes. Think about what a single new land cell can actually change.

Hint 2

A new land cell starts as its own island, then merges with each distinct neighboring island. Two neighbors might already be in the same island, so merging must only reduce the count when two different islands are joined.

Hint 3

Use a disjoint-set union (union-find) over flattened cell indices. Have union report whether it joined two different sets, and only then reduce the count. Skip orders that target cells that are already land.