DSA interview question
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].
vector<int> numIslands2(int m, int n, const vector<pair<int, int>>& positions);
Input (m, n, positions) | Output | Explanation |
|---|---|---|
(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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in