Google · Question 52 · Graphs
Number of Islands II
Problem
Given a list of positions to add land in a grid, return number of islands after each addition.
Approach
Use a Union-Find data structure to merge islands dynamically.
Time O(kα(mn))Space O(mn)
How it works
- 1Initialize Union-Find for all cells.
- 2For each position, add land and increment the island count.
- 3Union adjacent lands to merge islands.
- 4Append the current island count after each addition.
Sample input / output
Input: 3 3 4 0 0 0 1 1 2 2 1 Output: [1, 1, 2, 3]
Constraints
1 <= m, n, positions.length <= 10^4; 0 <= r < m; 0 <= c < n.
Solution — read it, then walk it
Time O(kα(mn))Space O(mn)Loops 2Branches 8Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/46
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits