PPractick

DSA interview question

Number of Islands II (Online Additions)

Hard · Data structures · Topics: graph, dsu, union find

The problem

A map starts as all water. Land is added one cell at a time, as volcanic islands rising from the sea, and after each addition the dashboard must show the current number of islands (4-directionally connected land). Re-running a flood fill after every addition costs O(m · n) each time. Union-find handles it online. A new land cell adds one island, and every successful union with a neighbouring land cell merges two islands, subtracting one. Adding a cell that's already land changes nothing.

Example: 3 × 3 grid, additions (0,0), (0,1), (1,2), (2,1) → [1, 1, 2, 3].

Function signature

vector<int> numIslands2(int m, int n, const vector<pair<int, int>>& positions);

Test cases

Input (m, n, positions)OutputExplanation
(3, 3, [[0,0],[0,1],[1,2],[2,1]])[1, 1, 2, 3](0,1) joins (0,0)
(2, 2, [[0,0],[1,1],[0,1]])[1, 2, 1](0,1) bridges two islands
(1, 3, [[0,0],[0,2],[0,1]])[1, 2, 1]
(3, 3, [[0,0],[0,0]])[1, 1]A repeat addition changes nothing
(1, 1, [[0,0]])[1]

(Confirm: connectivity is 4-directional; positions may repeat; the grid starts as all water.)

How interviewers phrase it

Clarifying questions to ask

  1. Can a position repeat? (Yes, and then the count is unchanged.)
  2. 4-directional? (Yes.)
  3. How many operations? (Up to 10⁴ on a large grid, so per-operation BFS is too slow.)

Follow-ups to expect

  1. "Why union-find?"
  2. "How does the count change?"
  3. "Why check roots before decrementing?"
  4. "What if land could also disappear?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in