Number of Islands II - 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 i-th 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.

Input & Output

Example 1 — Basic Island Formation
$ Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1,1,2,3]
💡 Note: Start empty. Add (0,0): 1 island. Add (0,1): connects to (0,0), still 1 island. Add (1,2): new island, now 2 total. Add (2,1): another new island, now 3 total.
Example 2 — Island Merging
$ Input: m = 2, n = 2, positions = [[0,0],[1,1],[0,1]]
Output: [1,2,1]
💡 Note: Add (0,0): 1 island. Add (1,1): separate island, 2 total. Add (0,1): connects (0,0) and (1,1) diagonally? No - only horizontal/vertical, so still 2 separate islands. Actually connects (0,0) vertically, merging into 1 island.

Constraints

  • 1 ≤ m, n ≤ 300
  • 1 ≤ positions.length ≤ 104
  • 0 ≤ ri < m
  • 0 ≤ ci < n

Visualization

Tap to expand
Number of Islands II: Dynamic Island Formation1123Final Grid StateProcessPosition Sequence[0,0] → 1 island[0,1] → 1 island (connected)[1,2] → 2 islands (separate)[2,1] → 3 islands (new)Output[1,1,2,3]🏝️ Islands form dynamically as land is addedConnected components merge when adjacent lands meet
Understanding the Visualization
1
Empty Grid
Start with 3×3 grid of all water (0s)
2
Add Lands
Process positions [[0,0],[0,1],[1,2],[2,1]]
3
Count Islands
Track island count after each addition: [1,1,2,3]
Key Takeaway
🎯 Key Insight: Use Union-Find to efficiently track connected components as they merge dynamically
Asked in
Google 28 Facebook 22 Amazon 18 Microsoft 15
89.4K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen