Minimum Number of Groups to Create a Valid Assignment Problem
Description
LeetCode Problem 2910.
You are given a collection of numbered balls and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:
- Balls with the same box must have the same value. But, if you have more than one ball with the same number, you can put them in different boxes.
- The biggest box can only have one more ball than the smallest box.
Return the fewest number of boxes to sort these balls following these rules.
Example 1:
Input: balls = [3,2,3,2,3]
Output: 2
Explanation:
We can sort balls into boxes as follows:
- [3,3,3]
- [2,2]
The size difference between the two boxes doesn't exceed one.
Example 2:
Input: balls = [10,10,10,3,1,1]
Output: 4
Explanation:
We can sort balls into boxes as follows:
- [10]
- [10,10]
- [3]
- [1,1]
You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Count Values and Try Group Sizes
Only the number of occurrences of each value matters, so count them with a hash table. Group sizes may differ by at most 1, so every group has size k or k + 1 for some k. A value that occurs v times is split into groups of those two sizes, so k can be at most the smallest count.
Try k from the smallest count down to 1. For a given k, a value with v occurrences can be split into sizes k and k + 1 exactly when v / k >= v % k (integer division): the v % k leftover elements must each be absorbed by a distinct group, turning it into size k + 1. If any value fails, skip this k. Otherwise use as many groups of size k + 1 as possible, which gives ceil(v / (k + 1)) groups for that value. Add these up. The first k that works is the largest one, and it gives the fewest groups, so we return it.
Complexity: O(n) time (there are d distinct values and k is at most n / d, so the loops do at most n steps), O(n) extra space.
class Solution:
def minGroupsForValidAssignment(self, nums: List[int]) -> int:
cnt = Counter(nums)
for k in range(min(cnt.values()), 0, -1):
ans = 0
for v in cnt.values():
if v // k < v % k:
ans = 0
break
ans += (v + k) // (k + 1)
if ans:
return ans