Minimum Number of Groups to Create a Valid Assignment - Problem

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:

Rule 1: Balls with the same number must be placed in the same box. However, if you have more than one ball with the same number, you can put them in different boxes.

Rule 2: The largest box can only have one more ball than the smallest box (difference ≤ 1).

Return the minimum number of boxes needed to sort these balls following these rules.

Input & Output

Example 1 — Basic Distribution
$ Input: nums = [1,1,2,2,3]
Output: 3
💡 Note: Frequencies: 1→2, 2→2, 3→1. Need 3 groups with sizes [2,2,1] to satisfy balance constraint (max-min ≤ 1)
Example 2 — All Same Numbers
$ Input: nums = [1,1,1,1]
Output: 2
💡 Note: All balls have same number, can split into 2 groups of size 2 each: [2,2]
Example 3 — Single Element
$ Input: nums = [5]
Output: 1
💡 Note: Only one ball, so minimum is 1 group

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Groups for Valid Assignment INPUT nums = [1,1,2,2,3] Collection of Numbered Balls: 1 1 2 2 3 Frequency Count: 1: 2 2: 2 3: 1 Rules: 1. Same numbers can split across multiple boxes 2. Max box size - Min box size <= 1 ALGORITHM STEPS 1 Count Frequencies Min freq = 1 (ball 3) 2 Try Group Sizes Try k=1, then k+1=2 3 Validate Distribution Each freq divisible by groups of size k or k+1 4 Calculate Min Boxes Sum groups needed With k=1 (sizes 1 or 2): Ball 1: 2 = 1 box of 2 Ball 2: 2 = 1 box of 2 Ball 3: 1 = 1 box of 1 Total = 1+1+1 = 3 boxes FINAL RESULT Optimal Box Assignment: Box 1 1 1 Box 2 2 2 Box 3 3 Box sizes: 2, 2, 1 Max - Min = 2 - 1 = 1 OK - Valid! Output: 3 Minimum boxes Key Insight: The optimal group size k must satisfy: each frequency can be split into groups of size k or k+1. We iterate k from minFreq down to 1, and for each valid k, calculate total groups needed. For freq f with group size k: groups = ceil(f / (k+1)). The answer is the minimum total across all valid k. TutorialsPoint - Minimum Number of Groups to Create a Valid Assignment | Optimal Solution
Asked in
Google 32 Meta 28 Amazon 25 Microsoft 20
32.4K Views
Medium Frequency
~25 min Avg. Time
875 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen