Talentd
FleetCode

3659. Partition Array Into K-Distinct Groups

Medium47.1% acceptance1 company

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 elements.
  • All elements in each group are distinct.
  • Each element in nums must 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 <= 105
  • 1 <= nums[i] <= 105
  • ​​​​​​​1 <= k <= nums.length

Asked at 1 company

Hints open one at a time

Hint 1
Think about how many groups of size k you need to form.
Hint 2
Each group must contain exactly k distinct elements.
Hint 3
If any element appears more times than the number of groups groups, it cannot be placed uniquely in each group.
Hint 4
Use a frequency map freq to count the occurrences of each element.
Hint 5
If the total number of elements n is not divisible by k, partitioning is impossible.
15:28
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def partitionArray(self, nums: List[int], k: int) -> bool:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,4]
2
Input
[3,5,2,2]
2
Input
[1,5,2,3]
3
Your code is saved on this device.Solution