← Uber bank

Uber · Question 40 · Graphs

Number of Islands II

GraphsPythoncode⏱ O(K×α(mn))💾 O(m×n)
Product-based

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

  1. 1Each new land starts as its own island.
  2. 2Union with existing neighbours to merge.
  3. 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.
yesnoyesnoyesnoyesnoyesnoyes↻ repeat↻ repeat↻ repeatyesSTARTm, n, positionsparent = {}rank = {}count = 0dirs = [(1, 0), (-1, 0),(0, 1), (0, -1)]DEFINE find(x)if parent[x] != xparent[x] = find(parent[x])RETURN parent[x]DEFINE union(a, b)nonlocal countra, rb = find(a), find(b)if ra == rbRETURNif rank[ra] < rank[rb]parent[ra] = rbelif rank[ra] >rank[rb]parent[rb] = raELSEparent[rb] = rarank[ra] += 1count -= 1res = []for r, c in positionsif (r, c) in parentres.append(count)CONTINUEparent[(r, c)] = (r, c)rank[(r, c)] = 0count += 1for dr, dc in dirsnr, nc = r + dr, c + dcif (nr, nc) in parentunion((r, c), (nr, nc))res.append(count)RETURN resDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it)); k =int(next(it))positions =[(int(next(it)),int(next(it))) for _ i…print(numIslands2(m, n,positions))if __name__ =="__main__"main()
  • 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