Skip to content
Preptima
mediumCodingMidSenior

Count the islands in a grid of land and water. Then land is added one cell at a time, and you report the island count after every addition.

For one grid, number of islands is a flood fill: each unvisited land cell starts a BFS or DFS, O(rows x cols). For land arriving cell by cell, rerunning that is too slow, so use union-find. Each new cell adds one island, and each union with a neighbour in a different set removes one, at near-constant amortised cost.

5 min readUpdated 2026-10-10Target archetype: Big Tech

Answer

Short answer

Number of islands on a fixed grid is a flood fill. Scan the cells, and every land cell not yet visited starts a BFS or DFS that marks its whole island. The count of flood fills is the answer, in O(rows × cols). When land arrives one cell at a time, keep a union-find over land cells instead. A new cell adds one island, and every union with a neighbour in a different set removes one, at near-constant amortised cost per addition.

Was this answer helpful?

Likely follow-ups

  • Cells can now turn back into water as well. Why does union-find stop helping, and what can you do if all operations are known in advance?
  • The grid is a billion cells per side but only a hundred thousand become land. How does your storage change?
  • Report the size of the largest island after each addition as well.
  • Diagonal neighbours now count as connected. What changes in the code and in the worst-case count of unions per addition?

Related questions

Related Topics