Minimum Incompatibility - Problem

You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.

A subset's incompatibility is the difference between the maximum and minimum elements in that array.

Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.

A subset is a group of integers that appear in the array with no particular order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,4], k = 2
Output: 4
💡 Note: Optimal distribution: [1,4] and [1,2]. Incompatibilities: (4-1) + (2-1) = 3 + 1 = 4
Example 2 — Impossible Case
$ Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
💡 Note: Each subset has size 2. Possible distribution: [1,2], [1,3], [3,6], [2,8] with incompatibilities 1+2+3+6=12, but optimal is different
Example 3 — All Same Elements
$ Input: nums = [5,5,5,5], k = 2
Output: -1
💡 Note: Cannot form 2 subsets without duplicate elements since all elements are the same

Constraints

  • 1 ≤ k ≤ nums.length ≤ 16
  • nums.length is divisible by k
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Minimum Incompatibility: Distribute Array into Equal Subsets1214Input: nums = [1,2,1,4], k = 2Subset 1Subset 2[1, 4][2, 1]Incomp: 4-1 = 3Incomp: 2-1 = 1Total Minimum Incompatibility: 3 + 1 = 4
Understanding the Visualization
1
Input
Array [1,2,1,4] with k=2 subsets needed
2
Distribute
Form 2 subsets of size 2 without duplicates within each
3
Calculate
Sum incompatibilities: (4-1) + (2-1) = 4
Key Takeaway
🎯 Key Insight: Use bitmask DP to efficiently explore all valid subset combinations while avoiding duplicate calculations
Asked in
Google 15 Facebook 8
12.0K Views
Medium Frequency
~45 min Avg. Time
234 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