Formatted question description: https://leetcode.ca/all/1282.html

# 1282. Group the People Given the Group Size They Belong To (Medium)

There are n people whose IDs go from 0 to n - 1 and each person belongs exactly to one group. Given the array groupSizes of length n telling the group size each person belongs to, return the groups there are and the people's IDs each group includes.

You can return any solution in any order and the same applies for IDs. Also, it is guaranteed that there exists at least one solution.

Example 1:

Input: groupSizes = [3,3,3,3,3,1,3]
Output: [,[0,1,2],[3,4,6]]
Explanation:
Other possible solutions are [[2,1,6],,[0,4,3]] and [,[0,6,2],[4,3,1]].


Example 2:

Input: groupSizes = [2,1,3,3,3,2]
Output: [,[0,5],[2,3,4]]


Constraints:

• groupSizes.length == n
• 1 <= n <= 500
• 1 <= groupSizes[i] <= n

Related Topics:
Greedy

## Solution 1.

The worst case for space complexity analysis is where we have the input in the form of [1, 2, 2, 3, 3, 3, ...]. Assume there are k distinct sizes, then k * (k + 1) / 2 = N, so the space complexity is O(sqrt(N)).

// OJ: https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/

// Time: O(N)
// Space: O(sqrt(N))
class Solution {
public:
vector<vector<int>> groupThePeople(vector<int>& A) {
unordered_map<int, int> m;
vector<vector<int>> ans;
for (int i = 0; i < A.size(); ++i) {
int sz = A[i];
if (m.count(sz) == 0 || ans[m[sz]].size() == sz) {
m[sz] = ans.size();
ans.emplace_back();
}
ans[m[sz]].push_back(i);
}
return ans;
}
};


Java

class Solution {
public List<List<Integer>> groupThePeople(int[] groupSizes) {
Map<Integer, List<Integer>> sizePeopleMap = new HashMap<Integer, List<Integer>>();
int length = groupSizes.length;
for (int i = 0; i < length; i++) {
int groupSize = groupSizes[i];
List<Integer> people = sizePeopleMap.getOrDefault(groupSize, new ArrayList<Integer>());
sizePeopleMap.put(groupSize, people);
}
List<List<Integer>> groups = new ArrayList<List<Integer>>();
Set<Integer> keySet = sizePeopleMap.keySet();
for (int groupSize : keySet) {
List<Integer> people = sizePeopleMap.get(groupSize);
int size = people.size();
if (size == groupSize)
else {
int groupsCount = size / groupSize;
for (int i = 0; i < groupsCount; i++) {
List<Integer> group = new ArrayList<Integer>();
int start = i * groupSize, end = (i + 1) * groupSize - 1;
for (int j = start; j <= end; j++)