Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Number of Groups to Create a Valid Assignment solution and explanation

MediumArrayGreedyHash Table6 min read25.0% acceptanceUpdated 9 Apr 2026
Minimum Number of Groups to Create a Valid Assignment Leetcode | Weekly Contest 368 | SolutionsAbhinav Awasthi · 10:35 · 2K viewsWatch on YouTube
8 more videos on this problem
  1. Minimum Number of Groups to Create a Valid Assignment Leetcode | Weekly Contest 368 | SolutionsAbhinav Awasthi · 10:35 · 2K views
  2. 2910. Minimum Number of Groups to Create a Valid Assignment - Weekly Contest 368TechTalk · 9:23 · 2K views
  3. 2910. Minimum Number of Groups to Create a Valid Assignment | Weekly Leetcode 368codingMohan · 36:41 · 2K views
  4. 2910. Minimum Number of Groups to Create a Valid Assignment || Maths 🔥 || T.C Brute Force 🔥Ayush Rao · 12:44 · 1K views
  5. 2910. Minimum Number of Groups to Create a Valid Assignment || Weekly Contest 368 || LeetcodeAshish Kumar · 18:32 · 506 views
  6. 2910. Minimum Number of Groups to Create a Valid Assignment (Leetcode Medium)Programming Live with Larry · 38:01 · 498 views
  7. 【每日一题】LeetCode 2910. Minimum Number of Groups to Create a Valid AssignmentHuifeng Guan · 19:30 · 249 views
  8. [Eng] Leetoce Weekly Contest 368 | 2910 Minimum Number of Groups to Create a Valid AssignmentCyCode · 14:09 · 76 views
  9. Minimum Number of Groups to Create a Valid Assignment in C++ | Full SolutionProgrammingGrand · 3:13 · 2 views

The 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:

  • 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 <= 105
  • 1 <= nums[i] <= 109

Approach overview

Problem Overview: You are given an array of integers and must split elements into groups so that each group contains identical values and the size difference between any two groups is at most 1. The goal is to minimize the total number of groups. Since elements with different values cannot mix, the problem reduces to analyzing the frequency of each value and distributing those counts into valid group sizes.

Approach 1: Greedy Distribution Based on Frequency (O(n + m * k) time, O(m) space)

Start by counting occurrences of each value using a hash map. If a value appears f times, you must split those f elements into groups whose sizes differ by at most 1. The greedy insight is to try the smallest feasible base group size derived from the minimum frequency across all values. For a candidate size k, check whether every frequency f can be expressed using groups of size k or k+1. Iterate possible k values from the minimum frequency downward and compute the required number of groups using integer division. This approach relies heavily on frequency counting via a hash table and a greedy choice that minimizes total groups while keeping group sizes balanced.

Approach 2: Balancing Frequency Distributions (O(n + m * k) time, O(m) space)

This method focuses on balancing the number of groups each frequency contributes. After building a frequency map, you treat each frequency as needing to be decomposed into several nearly equal groups. For a candidate base size x, compute how many groups are required if each group contains either x or x+1 elements. If a frequency cannot be distributed under that constraint, the candidate size is invalid and you try the next smaller size. The balancing step ensures the difference between group sizes never exceeds one. This approach combines ideas from greedy algorithms and counting techniques on arrays to systematically minimize the group count.

Recommended for interviews: The greedy frequency distribution approach is what most interviewers expect. It demonstrates that you can convert the problem into a frequency analysis task and reason about valid group sizes mathematically. A brute-force attempt to simulate group creation shows basic understanding, but the optimized greedy check shows stronger algorithmic insight and clean reasoning about constraints.

Approach 1: Greedy Distribution Based on Frequency

This approach focuses on counting the frequency of each unique ball type and distributing them into boxes, prioritizing minimizing deviation in box sizes.

from collections import Counter

def min_boxes(balls):
    frequency = Counter(balls)
    max_balls = max(frequency.values())
    boxes_needed = max_balls
    return boxes_needed

# Example usage
balls = [3, 2, 3, 2, 3]
print(min_boxes(balls))  # Output: 2
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int minBoxes(int[] balls) {
        Map<Integer, Integer> frequency = new HashMap<>();
        for (int ball : balls) {
            frequency.put(ball, frequency.getOrDefault(ball, 0) + 1);
        }
        int max_balls = 0;
        for (int count : frequency.values()) {
            max_balls = Math.max(max_balls, count);
        }
        return max_balls;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] balls = {3, 2, 3, 2, 3};
        System.out.println(sol.minBoxes(balls));  // Output: 2
    }
}

In this solution, we calculate the frequency of each ball using a Counter. The number of boxes is determined by the highest frequency of any single ball number. This ensures that while distributing, the max box count rule is maintained, as any imbalance would require fewer max frequency boxes than needed.

Complexity

Time Complexity: O(n), where n is the number of balls.
Space Complexity: O(n), storing the frequency count.

Try this approach in the editor

Approach 2: Balancing Frequency Distributions

This approach works by first computing the frequency of each ball type, then attempts to distribute the balls such that the resulting box configuration is balanced as specified.

#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;

int minBoxes(vector<int>& balls) {
    unordered_map<int, int> frequency;
    int max_balls = 0;
    for (int ball : balls) {
        frequency[ball]++;
        max_balls = max(max_balls, frequency[ball]);
    }
    return max_balls;
}

int main() {
    vector<int> balls = {3, 2, 3, 2, 3};
    cout << minBoxes(balls) << endl; // Output: 2
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int MinBoxes(int[] balls) {
        Dictionary<int, int> frequency = new Dictionary<int, int>();
        int max_balls = 0;
        foreach (int ball in balls) {
            if (!frequency.ContainsKey(ball)) {
                frequency[ball] = 0;
            }
            frequency[ball]++;
            max_balls = Math.Max(max_balls, frequency[ball]);
        }
        return max_balls;
    }

    public static void Main(string[] args) {
        Solution sol = new Solution();
        int[] balls = new int[] {3, 2, 3, 2, 3};
        Console.WriteLine(sol.MinBoxes(balls));  // Output: 2
    }
}

The C++ solution uses an unordered_map to track ball frequency and computes the number of required boxes by determining the maximum frequency. This ensures a nearly uniform distribution.

Complexity

Time Complexity: O(n), where n is the number of balls.
Space Complexity: O(n) for the frequency map.

Try this approach in the editor

Approach 3: Hash Table + Enumeration

We use a hash table cnt to count the number of occurrences of each number in the array nums. Let k be the minimum value of the number of occurrences, and then we can enumerate the size of the groups in the range [k,..1]. Since the difference in size between each group is not more than 1, the group size can be either k or k+1.

For the current group size k being enumerated, we traverse each occurrence v in the hash table. If \lfloor \frac{v}{k} \rfloor < v bmod k, it means that we cannot divide the occurrence v into k or k+1 groups with the same value, so we can skip this group size k directly. Otherwise, it means that we can form groups, and we only need to form as many groups of size k+1 as possible to ensure the minimum number of groups. Therefore, we can divide v numbers into \lceil \frac{v}{k+1} \rceil groups and add them to the current enumerated answer. Since we enumerate k from large to small, as long as we find a valid grouping scheme, it must be optimal.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.

function minGroupsForValidAssignment(nums: number[]): number {
    const cnt: Map<number, number> = new Map();
    for (const x of nums) {
        cnt.set(x, (cnt.get(x) || 0) + 1);
    }
    for (let k = Math.min(...cnt.values()); ; --k) {
        let ans = 0;
        for (const [_, v] of cnt) {
            if (((v / k) | 0) < v % k) {
                ans = 0;
                break;
            }
            ans += Math.ceil(v / (k + 1));
        }
        if (ans) {
            return ans;
        }
    }
}
func minGroupsForValidAssignment(nums []int) int {
	cnt := map[int]int{}
	for _, x := range nums {
		cnt[x]++
	}
	k := len(nums)
	for _, v := range cnt {
		k = min(k, v)
	}
	for ; ; k-- {
		ans := 0
		for _, v := range cnt {
			if v/k < v%k {
				ans = 0
				break
			}
			ans += (v + k) / (k + 1)
		}
		if ans > 0 {
			return ans
		}
	}
}
use std::collections::HashMap;

impl Solution {
    pub fn min_groups_for_valid_assignment(nums: Vec<i32>) -> i32 {
        let mut cnt: HashMap<i32, i32> = HashMap::new();

        for x in nums.iter() {
            let count = cnt.entry(*x).or_insert(0);
            *count += 1;
        }

        let mut k = i32::MAX;

        for &v in cnt.values() {
            k = k.min(v);
        }

        for k in (1..=k).rev() {
            let mut ans = 0;

            for &v in cnt.values() {
                if v / k < v % k {
                    ans = 0;
                    break;
                }

                ans += (v + k) / (k + 1);
            }

            if ans > 0 {
                return ans;
            }
        }

        0
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Greedy Distribution Based on Frequency

Time Complexity: O(n), where n is the number of balls.
Space Complexity: O(n), storing the frequency count.

Balancing Frequency Distributions

Time Complexity: O(n), where n is the number of balls.
Space Complexity: O(n) for the frequency map.

Hash Table + Enumeration–

Complexity analysis

ApproachTimeSpaceWhen to Use
Greedy Distribution Based on FrequencyO(n + m * k)O(m)General case; efficient when using frequency counting and testing valid group sizes
Balancing Frequency DistributionsO(n + m * k)O(m)Useful when reasoning about equalized group sizes and validating distributions mathematically

Frequently asked questions

Is Minimum Number of Groups to Create a Valid Assignment easy or hard?

The problem is rated Medium on LeetCode with an acceptance rate around 25%. The challenge comes from recognizing that the array itself is not important after counting frequencies. The real task is validating whether frequencies can be partitioned into nearly equal group sizes using a greedy check.

Minimum Number of Groups to Create a Valid Assignment Python/Java solution

Python and Java implementations typically start with a dictionary or HashMap to count frequencies. Then they iterate possible base group sizes and compute the number of groups needed using integer division and remainder checks. The logic is identical across languages, with differences only in syntax.

How to solve Minimum Number of Groups to Create a Valid Assignment in O(n)?

First build a frequency map of all values in the array. Determine the minimum frequency and iterate possible base group sizes from that value downward. For each candidate size k, verify that every frequency f can be split into groups of size k or k+1 using division checks. Once a valid configuration is found, sum the number of groups for all frequencies.

What is the best approach for Minimum Number of Groups to Create a Valid Assignment?

The greedy frequency distribution approach is typically the best solution. Count occurrences of each number with a hash map, then test feasible base group sizes derived from the minimum frequency. For each candidate size k, check whether every frequency can be split into groups of size k or k+1. This minimizes the total number of groups while keeping group sizes balanced.

Is Minimum Number of Groups to Create a Valid Assignment asked at Google/Amazon/Meta?

Problems involving frequency grouping and greedy distribution frequently appear in interviews at companies like Google, Amazon, and Meta. This specific LeetCode problem tests reasoning about constraints, counting with hash maps, and greedy validation, which are common interview patterns.

What data structure is used in Minimum Number of Groups to Create a Valid Assignment?

The core data structure is a hash map that stores the frequency of each value in the array. After counting, the algorithm iterates over these frequencies and applies greedy arithmetic checks to determine how many groups are needed for each value.

What is the time complexity of Minimum Number of Groups to Create a Valid Assignment?

The overall time complexity is roughly O(n + m * k), where n is the array length, m is the number of distinct values, and k is the number of candidate group sizes tested. Frequency counting takes O(n), and validation across frequencies is usually small in practice, making the solution close to linear time.

Comments

Now write it yourselfClose this page and solve Minimum Number of Groups to Create a Valid Assignment in the editor, without looking.
Practise Minimum Number of Groups to Create a Valid Assignment