Uber · Question 40 · Graphs
Number of Islands II
Problem
Given m, n and a list of positions where land is added sequentially in an all - water grid, return the number of islands after each addition.
Approach
Use Union-Find to dynamically union newly added land with adjacent lands, maintaining the count of distinct islands.
Time O(K×α(mn))Space O(m×n)
How it works
- 1Each new land starts as its own island.
- 2Union with existing neighbours to merge.
- 3Record the 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; valid positions.
Solution — read it, then walk it
Time O(K×α(mn))Space O(m×n)Loops 2Branches 8Returns 3source · 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