[LeetCode] Partition Array Into K-Distinct Groups

3659. Partition Array Into K-Distinct Groups

You are given an integer array nums and an integer k.

Your task is to determine whether it is possible to partition all elements of nums into one or more groups such that:

  • Each group contains exactly k distinct elements.
  • Each element in nums must be assigned to exactly one group.

Return true if such a partition is possible, otherwise return false.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool partitionArray(vector<int>& nums, int k) {
unordered_map<int,int> freq;
int ma = 0, n = nums.size();
if(n % k) return false;
for(auto& n : nums) {
ma = max(ma, ++freq[n]);
}
return ma <= n / k;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/08/25/PS/LeetCode/partition-array-into-k-distinct-groups/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.