305. Number of Islands II - Detailed Explanation
Problem Statement
You have an m × n grid initially filled with water. You are given a sequence of positions, each a pair [r, c] where you turn the cell (r,c) into land. After each addition, report the total number of connected islands (4‑directionally adjacent groups of land cells).
Input
- Integers
m,n positions: list of k pairs[r, c]with0 ≤ r < m,0 ≤ c < n
Output
- List of k integers, where the _i_th integer is the number of islands after processing
positions[i]
Example
m = 3, n = 3
positions = [[0,0],[0,1],[1,2],[2,1]]
Output → [1,1,2,3]
Constraints
- 1 ≤ m, n ≤ 10⁴
- 1 ≤ positions.length ≤ 10⁴
- Positions may repeat (adding land to an already-land cell has no effect)
Hints
- Brute‑force after each addition, run a full DFS/BFS to count islands, but that’s O(m × n) per query.
- Map each cell
(r,c)to a 1D indexidx = r*n + c. - Use a Union‑Find structure where each newly added land starts as its own set (increment count), then union with any adjacent lands (decrement count on each successful union).
Brute Force Approach
- Maintain a grid of water/land.
- After each addition, run a full DFS/BFS from every unvisited land cell to count connected components.
- Time: O(k × m × n) in worst case
- Space: O(m × n)
Optimized Union‑Find Approach
-
Initialization
parentarray of sizem*n, initialized to -1 (water)rank(or size) array of sizem*n, all zeroscount = 0
-
addLand(r, c)
- Compute
idx = r*n + c. - If
parent[idx] != -1, it’s already land → append currentcountand return. - Set
parent[idx] = idx,rank[idx] = 1,count++. - For each of the four neighbors
(r+dr, c+dc)within bounds:- Let
nidx = nr*n + nc. Ifparent[nidx] != -1, union(idx,nidx). On each successful union, docount--.
- Let
- Append
countto the result list.
- Compute
-
Union & Find
- find(x) with path compression
- union(x, y) by rank/size, return
trueif two roots were distinct
This yields amortized O(α(m × n)) per operation, effectively O(1).
Step‑by‑Step Walkthrough
m=3, n=3, positions=[[0,0],[0,1],[1,2],[2,1]]
- Start: all water, count=0
- Add (0,0) → idx=0
- parent[0]=0, count=1
- neighbors water → no unions
→ result=[1]
- Add (0,1) → idx=1
- parent[1]=1, count=2
- neighbor left idx=0 is land → union(1,0): roots differ → merge → count=1
→ result=[1,1]
- Add (1,2) → idx=1*3+2=5
- parent[5]=5, count=2
- no adjacent land → result=[1,1,2]
- Add (2,1) → idx=2*3+1=7
- parent[7]=7, count=3
- neighbor up idx=4 water, left idx=6 water, right idx=8 water, down out
→ result=[1,1,2,3]
Complexity Analysis
- Time: O(k × α(m × n)) ≈ O(k)
- Space: O(m × n) for
parentandrankarrays
Code Solutions
Python
Python3
Python3
. . . .
Java Code
Java
Java
. . . .
Common Mistakes
- Not mapping 2D → 1D indices correctly (
idx = r*n + c). - Forgetting to check for repeated additions (land already present).
- Off‑by‑one errors in neighbor loops or bounds checks.
- Neglecting to decrement the island count on successful union.
Edge Cases
- Duplicate positions: must ignore and report same count.
- No positions: return an empty list.
- m = 0 or n = 0: grid has no cells → always zero islands.
- All positions outside bounds: treat as no‑ops.
Alternative Variations
- Number of Islands (static) – LeetCode 200: count islands once via DFS/BFS.
- Number of Connected Components in an undirected graph (LeetCode 323).
- Dynamic Connectivity with edge additions/removals.
Related Problems
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-
GET YOUR FREE
Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
129. Sum Root to Leaf Numbers - Detailed Explanation
Learn to solve Leetcode 129. Sum Root to Leaf Numbers with multiple approaches.
1344. Angle Between Hands of a Clock - Detailed Explanation
Learn to solve Leetcode 1344. Angle Between Hands of a Clock with multiple approaches.
2851. String Transformation - Detailed Explanation
Learn to solve Leetcode 2851. String Transformation with multiple approaches.
1378. Replace Employee ID With The Unique Identifier - Detailed Explanation
Learn to solve Leetcode 1378. Replace Employee ID With The Unique Identifier with multiple approaches.
2257. Count Unguarded Cells in the Grid - Detailed Explanation
Learn to solve Leetcode 2257. Count Unguarded Cells in the Grid with multiple approaches.
125. Valid Palindrome - Detailed Explanation
Learn to solve Leetcode 125. Valid Palindrome with multiple approaches.
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
4.6
(69,299 learners)
$197
New

Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
(1,107 learners)
$78
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
(26,683 learners)
$78
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.