Count islands by requested sizes
Problem
You are given a 2D grid of characters '0' and '1', where '1' represents land and '0' represents water. An island is defined as a maximal group of horizontally or vertically (4-directionally) adjacent land cells.
The size of an island is the total number of land cells within that island.
You are also provided with an integer array queries, where each element represents a specific island size to query.
Your task is to return an integer array ans of the same length as queries. For each i, ans[i] should be equal to 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], the expected output ans would be [2, 0, 5, 0].
Constraints
1 <= rows, cols <= 2000grid[r][c] ∈ {'0','1'}1 <= queries.length <= 2e5- Query sizes are positive integers
Notes
- Use 4-directional adjacency only (no diagonals).
queriesmay contain duplicates; return counts for each position.
AI interview prep
Core dilemma
Balancing the one-time cost of traversing a potentially large grid (up to 4 million cells) to discover all island sizes against the efficiency of answering a large number of queries (up to 200,000) for those sizes.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Count islands by requested sizes
Problem
You are given a 2D grid of characters '0' and '1', where '1' represents land and '0' represents water. An island is defined as a maximal group of horizontally or vertically (4-directionally) adjacent land cells.
The size of an island is the total number of land cells within that island.
You are also provided with an integer array queries, where each element represents a specific island size to query.
Your task is to return an integer array ans of the same length as queries. For each i, ans[i] should be equal to 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], the expected output ans would be [2, 0, 5, 0].
Constraints
1 <= rows, cols <= 2000grid[r][c] ∈ {'0','1'}1 <= queries.length <= 2e5- Query sizes are positive integers
Notes
- Use 4-directional adjacency only (no diagonals).
queriesmay contain duplicates; return counts for each position.