Problem · Matrix
Count One Groups by Size
Learn this problemProblem statement
In a square grid, two cells are connected if they share an edge and contain the same value. Sharing an edge means up, down, left, or right, but not diagonal.
Given a square integer grid grid and an array queries, consider only connected groups of cells whose value is 1. For each query value, return how many connected groups of 1s have size exactly equal to that query.
Return an array where the i-th element is the answer for queries[i].
Function
onesGroups(grid: int[][], queries: int[]) → int[]Examples
Example 1
grid = [[1,1,1,1,1,1],[1,1,0,0,0,0],[0,0,0,1,1,1],[0,0,0,1,1,1],[0,0,1,0,0,0],[1,0,0,0,0,0]]queries = [6,1,8,2]return = [1,2,1,0]The grid contains four connected groups of 1s: one group with 8 cells, one group with 6 cells, and two groups with 1 cell. Therefore the answers for [6,1,8,2] are [1,2,1,0].
Constraints
gridis a non-empty square matrix.grid[i][j]is either0or1.queries.length >= 1
More Agoda problems
- Minimum Absolute Difference PairsONSITE INTERVIEW · Seen Jun 2026
- Feasibility of Printing Within Given DaysONSITE INTERVIEW · Seen May 2026
- Minimum Daily Printing LimitONSITE INTERVIEW · Seen May 2026
- 3SumONSITE INTERVIEW · Seen May 2026
- Minimum Price With Discount CouponsOA · Seen Jul 2025
- Lexicographically Smallest Task QueueOA · Seen Jul 2025
- Team FormationOA · Seen Apr 2025
- Two-Core Process AssignmentOA · Seen Apr 2025