Partition Array Into K-Distinct Groups Problem
#3659
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3659.
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
kelements. - All elements in each group are distinct.
- Each element in
numsmust be assigned to exactly one group.
Return true if such a partition is possible, otherwise return false.
Example 1:
Input: nums = [1,2,3,4], k = 2
Output: true
Explanation:
One possible partition is to have 2 groups:
- Group 1: [1, 2]
- Group 2: [3, 4]
Each group contains k = 2 distinct elements, and all elements are used exactly once.
Example 2:
Input: nums = [3,5,2,2], k = 2
Output: true
Explanation:
One possible partition is to have 2 groups:
- Group 1: [2, 3]
- Group 2: [2, 5]
Each group contains k = 2 distinct elements, and all elements are used exactly once.
Example 3:
Input: nums = [1,5,2,3], k = 3
Output: false
Explanation:
We cannot form groups of k = 3 distinct elements using all values exactly once.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= k <= nums.length
Solution
Approach: Counting
Let n be the array length. Every group has exactly k elements, so if n is not divisible by k the answer is false.
Otherwise there are m = n / k groups. Each group can hold a given value at most once, so a value that occurs more than m times cannot be placed. If no value occurs more than m times, the elements can always be spread over the m groups, so the answer is true.
Complexity: time O(n), space O(n).
class Solution:
def partitionArray(self, nums: List[int], k: int) -> bool:
m, mod = divmod(len(nums), k)
if mod:
return False
return max(Counter(nums).values()) <= m