Count Islands After Land Additions
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of dynamic connectivity, incremental graph updates, and algorithmic efficiency when maintaining connected components under repeated modifications.
Constraints
- 1 <= m, n <= 10^4
- 0 <= len(positions) <= 10^5
- 0 <= row < m and 0 <= col < n for every position
- positions may contain duplicate coordinates
Examples
Input: (3, 3, [[0, 0], [0, 1], [1, 2], [2, 1], [1, 1]])
Expected Output: [1, 1, 2, 3, 1]
Explanation: The first two additions form one island, then two separate islands are created, and the final addition connects all land into a single island.
Input: (1, 1, [[0, 0], [0, 0], [0, 0]])
Expected Output: [1, 1, 1]
Explanation: Adding the same single cell multiple times does not change the island count after the first addition.
Input: (2, 2, [])
Expected Output: []
Explanation: No land additions means there are no intermediate island counts to report.
Input: (2, 2, [[0, 0], [1, 1], [0, 1], [1, 0], [1, 0]])
Expected Output: [1, 2, 1, 1, 1]
Explanation: Two separate islands are created, then merged into one by [0, 1]. Adding [1, 0] keeps everything connected, and the duplicate final addition changes nothing.
Input: (1, 3, [[0, 0], [0, 2], [0, 1]])
Expected Output: [1, 2, 1]
Explanation: The middle cell connects the two end cells into one island.
Hints
- Recomputing the number of islands with a full BFS or DFS after every addition will be too slow.
- Use a Disjoint Set Union (Union-Find) structure to connect newly added land with its existing neighboring land cells and maintain the island count incrementally.