Published at Apr 19, 2020

Group the People Given the Group Size They Belong To in Python


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.

Input: groupSizes = [3,3,3,3,3,1,3]

Output: [[5],[0,1,2],[3,4,6]]

Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].


groupSizes.length == n

1 <= n <= 500

1 <= groupSizes[i] <= n


from collections import defaultdict

class Solution:
  def groupThePeople(groupSizes):
    count = defaultdict(list)
    for i, size in enumerate(groupSizes):
    result = []

    for s, value in count.items():
      for index in range(0, len(value), s):
        result.append(value[index:index + s])
    return result

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