
Sponsored
Sponsored
This approach involves using a hashmap (or dictionary) to keep track of members that belong to groups of the same size. You iterate over the groupSizes array, and for each person, add their ID to a list associated with their required group size in the hashmap. Once a list reaches the intended group size, you add it to the result and reset the list for that group size.
The time complexity is O(n), where n is the number of people, because each person is processed exactly once. The space complexity is also O(n), because we store the people in an intermediate dictionary before creating the result.
1var groupThePeople = function(groupSizes) {
2 const sizeToPeople = new Map();
3 const result = [];
4 groupSizes.forEach((size, index) => {
5 if (!sizeToPeople.has(size)) {
6 sizeToPeople.set(size, []);
7 }
8 sizeToPeople.get(size).push(index);
9 if (sizeToPeople.get(size).length === size) {
10 result.push(sizeToPeople.get(size));
11 sizeToPeople.set(size, []);
12 }
13 });
14 return result;
15};In JavaScript, we use a Map to track lists of people by their group size. As we add people, the lists are checked for completeness, and full lists are appended to the result, after which the entry is cleared.
This approach uses direct index management without using a hashmap, iterating through the list and directly placing IDs into result groups once a correct-sized group is filled, simplifying the storage by maintaining an array or linked list for each group size.
The time complexity is O(n), and similarly, space complexity is O(n) due to linear storage requirements.
The Python solution manages arrays directly for each group size. As people are processed, they are appended to their respective list. Once full, the list is added to the list of results and reset.