By Vivek - April 19, 2020
Group People by Group Size in Python
Problem:
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]]
Explanation:
Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]]. Constraints:
groupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n Solution:
from collections import defaultdict
class Solution:
def groupThePeople(groupSizes):
count = defaultdict(list)
for i, size in enumerate(groupSizes):
count[size].append(i)
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]
print(Solution.groupThePeople(groupSizes)) Related Posts
- K-Concatenation Maximum Sum in Python
- Maximum Subarray Sum with One Deletion in Python
- Reverse Parentheses Substrings in Python
- Count Servers that Communicate in Python
- Count Square Submatrices with All Ones in Python
- Find Winner on a Tic Tac Toe Game in Python
- Minimum Absolute Difference in Python
- Minimum Time Visiting All Points in Python
- Number of Burgers with No Waste of Ingredients in Python
- Search Suggestions System in Python