
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.
1#include <vector>
2#include <unordered_map>
3using namespace std;
4
5vector<vector<int>> groupThePeople(vector<int>& groupSizes) {
6 unordered_map<int, vector<int>> size_to_people;
7 vector<vector<int>> result;
8 for (int i = 0; i < groupSizes.size(); ++i) {
9 int size = groupSizes[i];
10 size_to_people[size].push_back(i);
11 if (size_to_people[size].size() == size) {
12 result.push_back(size_to_people[size]);
13 size_to_people[size].clear();
14 }
15 }
16 return result;
17}This C++ implementation uses an unordered_map to map each group size to the list of people requiring that group size. As each person is processed, their ID is added to the map. When a group reaches the required size, it is added to the result vector and the entry for that size 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.