Group the People Given the Group Size They Belong To

Updated on 13 June, 2025
Group the People Given the Group Size They Belong To header image

Problem Statement

In this task, n individuals are segmented into an indeterminate number of groups. Each individual is uniquely identified by labels ranging from 0 to n - 1. You are provided with an array groupSizes where the element at each index i indicates the required size of the group for person i. For instance, if groupSizes[1] = 3, person 1 is destined to belong to a group that contains a total of three members.

You are required to orchestrate these individuals into groups in such a way that each person i finds themselves in a group of the size specified by groupSizes[i]. Every individual must be part of exactly one group. The solution must heed to the given group size constrains for each individual, and it is important to note that multiple valid groupings might exist for the same set of inputs. However, it is assured that there is at least one feasible solution that can be derived from the given inputs.

Examples

Example 1

Input:

groupSizes = [3,3,3,3,3,1,3]

Output:

[[5],[0,1,2],[3,4,6]]
**Explanation:**
The first group is [5]. The size is 1, and groupSizes[5] = 1.
The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.
The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

Example 2

Input:

groupSizes = [2,1,3,3,3,2]

Output:

[[1],[0,5],[2,3,4]]

Constraints

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

Approach and Intuition

The problem prompts us to group individuals based on the size specified in the groupSizes array. We can efficiently achieve this by leveraging a dictionary (or hash map) to keep track of group members according to their intended group size. Here’s a structured method to solve the problem:

  1. Begin by initializing a dictionary named groups where keys represent the group size and values are lists that store the indices (or IDs) of the individuals.

  2. Traverse through the given groupSizes array. For each individual i, do the following:

    • Add the individual i to the list corresponding to their desired group size in groups.
    • Check if the number of individuals in this list reaches the group size (i.e., if the list size matches the group size key). When a list becomes full:
      • Append this completed group to the final answer list.
      • Reset the list for that particular group size in the dictionary to start forming the next group of the same size.
  3. Continue the above steps until all individuals are successfully grouped.

This method efficiently groups individuals as it processes each person exactly once. It ensures that everyone is placed in a group that matches their specified size, respecting the constraints given. The ultimate complexity of this approach is O(n) since each individual's grouping is determined in a single pass of the array.

Solutions

  • C++
  • Java
cpp
class Solution {
public:
    vector<vector<int>> organizeGroupSizes(vector<int>& sizes) {
        vector<vector<int>> result;
        
        vector<int> sizeMap[sizes.size() + 1];
        for (int idx = 0; idx < sizes.size(); idx++) {
            sizeMap[sizes[idx]].push_back(idx);
            
            if (sizeMap[sizes[idx]].size() == sizes[idx]) {
                result.push_back(sizeMap[sizes[idx]]);
                sizeMap[sizes[idx]].clear();
            }
        }
        
        return result;
    }
};

The given C++ code solves the problem of organizing people into groups according to the size they belong to. The function organizeGroupSizes accepts a vector of integers where each integer represents the desired group size for each person. The code follows these steps:

  1. Initialize result as a vector of vector of integers, which will store the final groupings.
  2. Create an array sizeMap of vectors to temporarily hold the indices of people until the group reaches the desired size.
  3. Loop through each person's index in the given sizes vector using a for loop.
    • For each person, add their index to the corresponding vector in sizeMap based on their desired group size.
    • Check if the size of this vector matches the desired group size (sizes[idx]). If it does, add this group to result and clear the vector in sizeMap for potential reuse for other groups of the same size.

The approach efficiently groups people by iterating through the list just once and using direct access via the array of vectors, making the solution robust and optimized for the task. The code uses simple operations on vectors to manage indices and check for completeness of groups, ensuring that all the conditions of the problem are met effectively.

java
class Solution {
    public List<List<Integer>> organizeGroups(int[] sizes) {
        List<List<Integer>> results = new ArrayList<>();
        
        Map<Integer, List<Integer>> sizeMap = new HashMap<>();
        for (int idx = 0; idx < sizes.length; idx++) {
            if (!sizeMap.containsKey(sizes[idx])) {
                sizeMap.put(sizes[idx], new ArrayList<>());
            }
            
            List<Integer> currentGroup = sizeMap.get(sizes[idx]);
            currentGroup.add(idx);

            if (currentGroup.size() == sizes[idx]) {
                results.add(currentGroup);
                sizeMap.remove(sizes[idx]);
            }
        }

        return results;
    }
}

The given Java program is designed to group people according to the sizes they belong to. This problem requires the arrangement of individuals into specific group sizes as indicated by input values. The method organizeGroups takes an array sizes where each element represents a person and the number indicates the group size they should be part of.

  • The method employs a hashmap (sizeMap) to track which person belongs to which group size.
  • As the program iterates through the sizes array:
    • If the group size (key) is not already in sizeMap, a new entry with an empty list is created.
    • The current person (indexed by idx) is added to the appropriate group in sizeMap.
    • When a group reaches its required size, indicated by the list's length matching the group size key, it's added to the result list results.
    • After transferring to results, that group is removed from sizeMap to avoid any further additions to a complete group.

The final output, results, is a list of lists, where each sublist corresponds to a group of people configured according to the rules defined by their group sizes. This approach ensures all participants are correctly grouped and no group exceeds its intended capacity.

Comments

No comments yet.