Count Land Masses as Map Tiles Are Added One by One
Last updated: November 29, 2026
Quick Overview
An m by n map starts as all water. A sequence of positions is turned into land one at a time. After each addition, return the number of islands, where an island is a group of land cells connected horizontally or vertically.
Meta
November 29, 20260
0
0 solved
An m by n map starts as all water. A sequence of positions is turned into land one at a time. After each addition, return the number of islands, where an island is a group of land cells connected horizontally or vertically.
A hard Meta onsite question that tests online connectivity, framed around a map rendering service that updates region counts as tiles load. The interviewer checks that you avoid re-running flood fill after every addition and instead union the new cell with its land neighbors, adjusting the count in O(alpha) per neighbor.
What the Interviewer Expects
- Use union find keyed by flattened cell index
- Increment the count for each new land cell
- Union with up to four land neighbors, decrementing on each successful merge
- Ignore repeated additions of the same cell
- State O(k * alpha(mn)) time for k additions
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you support turning land back into water?
- What if the grid is effectively infinite, like a world map?
- How would you also report the size of the largest island after each step?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
m,n, andpositionsas[r, c]. - Output: list of island counts after each addition.
- The same position may appear more than once....
High-Level Design
Recomputing islands with BFS after each addition is O(k * m * n). Instead keep a union find over cells that are land:
- If the cell is already land, the count is unchanged.
- Otherwise mark it la...