Solve island and frequency problems
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: These problems evaluate graph traversal and connected-component identification in 2D grids plus frequency analysis and selection in arrays, covering concepts such as DFS/BFS, Union-Find, hashing, heaps and bucket sort.
Constraints
- 0 <= m, n <= 1000, where m = number of rows, n = number of columns
- m * n <= 200000
- All rows have equal length
- grid[i][j] is 0 or 1
- 0 <= k <= 100000
- Islands are connected 4-directionally (up, down, left, right)
- If k exceeds the number of distinct area values, return all distinct areas
- Order result by frequency descending, then by area value descending
Hints
- Traverse the grid and use BFS/DFS to compute each island's area.
- Collect all island areas, then count frequencies with a hash map.
- Use a heap to extract top-k by (frequency desc, area desc), e.g., push (-freq, -area).
- Return early for k == 0 or when the grid is empty.