Count islands by requested sizes
Company: Bloomberg
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
You are given a 2D grid of characters `'0'` and `'1'`, where `'1'` represents land and `'0'` represents water. An **island** is a maximal group of horizontally/vertically (4-directionally) adjacent land cells.
The **size** of an island is the number of land cells in that island.
You are also given an integer array `queries`, where each element is a size to query.
Return an integer array `ans` of the same length as `queries`, where `ans[i]` equals the number of islands in the grid whose size is exactly `queries[i]`.
### Example
If the grid contains:
- 2 islands of size 10
- 0 islands of size 1
- 5 islands of size 2
- 0 islands of size 3
Then for `queries = [10, 1, 2, 3]`, return `ans = [2, 0, 5, 0]`.
### Constraints (reasonable interview defaults)
- `1 <= rows, cols <= 2000` (or smaller depending on the language/time limit)
- `grid[r][c] ∈ {'0','1'}`
- `1 <= queries.length <= 2e5`
- Query sizes are positive integers
### Notes
- Use 4-directional adjacency only (no diagonals).
- `queries` may contain duplicates; return counts for each position.
Quick Answer: This question evaluates a candidate's understanding of grid connectivity, identification of connected components, and the ability to aggregate component sizes for frequency queries.
For each query size, return how many 4-directional islands in the grid have exactly that size.
Constraints
- grid contains '0' and '1'
Examples
Input: ([['1', '1', '0'], ['0', '1', '0'], ['0', '0', '1']], [3, 1, 2])
Expected Output: [1, 1, 0]
Explanation: One size-3 island and one size-1 island.
Input: ([['0', '0', '0']], [1])
Expected Output: [0]
Explanation: No land.
Input: ([['1', '0', '1'], ['1', '0', '1']], [2, 1])
Expected Output: [2, 0]
Explanation: Two vertical islands of size 2.
Hints
- Flood-fill each island once and count island sizes.