cswork / libraryOpen practice workspace

Interview questions · Spacex

Dynamic Island Counts

Report the exact island count after each land addition by tracking only activated cells and merging distinct neighboring components efficiently.

Implement island_counts(rows: int, columns: int, additions: list[list[int]]) -> list[int].

Begin with a rows by columns grid containing only water. Each addition [row, column] changes that cell to land. After every addition, return the current number of islands, where land connects only through shared horizontal or vertical edges.

Input Domain

  • 1 <= rows, columns <= 100,000 and rows * columns <= 10^9.
  • 0 <= len(additions) <= 200,000.
  • Every addition contains exactly two valid zero-based coordinates.
  • The same coordinate may be added more than once.

Output Rules

  • Preserve the order of additions.
  • Adding a cell that is already land changes nothing but still produces an output count.
  • Diagonal neighbors do not connect islands.
  • Return an empty list when there are no additions.

Constraints

  • The result after each operation must be exact.
  • Space should depend on the number of distinct added cells, not on rows * columns.

Examples

Example 1

Input: rows = 3, columns = 3, additions = [[0,0],[0,1],[1,2],[2,1]]

Output: [1,1,2,3]

Example 2

Input: rows = 2, columns = 3, additions = [[0,0],[0,2],[0,1],[0,1]]

Output: [1,2,1,1]

Hint: Merge newly connected components

A new land cell begins as one component, then each union with a distinct neighboring component reduces the count by one.

Community answers

Nothing here yet.

Join in on CSWork →