← Google bank

Google · Question 52 · Graphs

Number of Islands II

GraphsPythoncode⏱ O(kα(mn))💾 O(mn)
Product-based

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

  1. 1Initialize Union-Find for all cells.
  2. 2For each position, add land and increment the island count.
  3. 3Union adjacent lands to merge islands.
  4. 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.
yesnoyesnoyesnoyesnoyesnoyes↻ repeat↻ repeat↻ repeatyesSTARTCLASS UnionFindDEFINE __init__(self, n)self.parent =list(range(n))self.rank = [0] * nself.count = 0DEFINE find(self, x)if self.parent[x] != xself.parent[x] =self.find(self.parent[x])RETURN self.parent[x]DEFINE union(self, x, y)rootX, rootY =self.find(x), self.find(y)if rootX != rootYif self.rank[rootX] >self.rank[rootY]self.parent[rootY] = rootXelif self.rank[rootX]< self.rank[rootY]self.parent[rootX] = rootYELSEself.parent[rootY] = rootXself.rank[rootX] += 1self.count -= 1DEFINE numIslands2(m, n,positions)uf = UnionFind(m * n)grid = [[0] * n for _ inrange(m)]res = []for r, c in positionsif grid[r][c] == 1res.append(uf.count)CONTINUEgrid[r][c] = 1uf.count += 1idx = r * n + cfor nr, nc in [(r - 1,c), (r + 1, c), (r, c- 1), (r, c + 1)]if 0 <= nr < m and 0<= nc < n andgrid[nr][nc] == 1uf.union(idx, nr * n + nc)res.append(uf.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