Problem Description
Given an integer array groupSizes where each element groupSizes[i] represents the size of the group that person i must belong to, partition all persons labeled from 0 to n - 1 into groups such that each person is in exactly one group matching the required size. Return any valid grouping.
Key Insights
- Use a hash map to bucket persons by their required group sizes.
- Accumulate person indices in the bucket corresponding to groupSizes[i].
- Once a bucket reaches the size equal to its key, add that bucket as a valid group and clear it.
- This greedy grouping ensures each group meets the constraints.
Space and Time Complexity
Time Complexity: O(n), where n is the number of persons. Space Complexity: O(n), since we use additional storage for the hashmap and the result list.
Solution
We initialize a hashmap (or dictionary) to map each required group size to a list of person indices with that requirement. As we iterate through the array:
- Add the current person to the corresponding bucket.
- If the bucket's length becomes equal to the required group size, finalize that bucket as a group, append it to the result, and reset the bucket. This approach guarantees a valid partitioning in linear time using extra space proportional to n.