Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 integers that appear in the array with no particular order.
Example 1:
Input: nums = [1,2,1,4], k = 2 Output: 4 Explanation: The optimal distribution of subsets is [1,2] and [1,4]. The incompatibility is (2-1) + (4-1) = 4. Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input: nums = [6,3,8,1,3,1,2,2], k = 4 Output: 6 Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3]. The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input: nums = [5,3,3,6,3,3], k = 3 Output: -1 Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16nums.length is divisible by k1 <= nums[i] <= nums.lengthProblem summary: 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 integers that appear in the array with no particular order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Bit Manipulation
[1,2,1,4] 2
[6,3,8,1,3,1,2,2] 4
[5,3,3,6,3,3] 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1681: Minimum Incompatibility
class Solution {
public int minimumIncompatibility(int[] nums, int k) {
int n = nums.length;
int m = n / k;
int[] g = new int[1 << n];
Arrays.fill(g, -1);
for (int i = 1; i < 1 << n; ++i) {
if (Integer.bitCount(i) != m) {
continue;
}
Set<Integer> s = new HashSet<>();
int mi = 20, mx = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
if (!s.add(nums[j])) {
break;
}
mi = Math.min(mi, nums[j]);
mx = Math.max(mx, nums[j]);
}
}
if (s.size() == m) {
g[i] = mx - mi;
}
}
int[] f = new int[1 << n];
final int inf = 1 << 30;
Arrays.fill(f, inf);
f[0] = 0;
for (int i = 0; i < 1 << n; ++i) {
if (f[i] == inf) {
continue;
}
Set<Integer> s = new HashSet<>();
int mask = 0;
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 0 && !s.contains(nums[j])) {
s.add(nums[j]);
mask |= 1 << j;
}
}
if (s.size() < m) {
continue;
}
for (int j = mask; j > 0; j = (j - 1) & mask) {
if (g[j] != -1) {
f[i | j] = Math.min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] == inf ? -1 : f[(1 << n) - 1];
}
}
// Accepted solution for LeetCode #1681: Minimum Incompatibility
func minimumIncompatibility(nums []int, k int) int {
n := len(nums)
m := n / k
const inf = 1 << 30
f := make([]int, 1<<n)
g := make([]int, 1<<n)
for i := range g {
f[i] = inf
g[i] = -1
}
for i := 1; i < 1<<n; i++ {
if bits.OnesCount(uint(i)) != m {
continue
}
s := map[int]struct{}{}
mi, mx := 20, 0
for j, x := range nums {
if i>>j&1 == 1 {
if _, ok := s[x]; ok {
break
}
s[x] = struct{}{}
mi = min(mi, x)
mx = max(mx, x)
}
}
if len(s) == m {
g[i] = mx - mi
}
}
f[0] = 0
for i := 0; i < 1<<n; i++ {
if f[i] == inf {
continue
}
s := map[int]struct{}{}
mask := 0
for j, x := range nums {
if _, ok := s[x]; !ok && i>>j&1 == 0 {
s[x] = struct{}{}
mask |= 1 << j
}
}
if len(s) < m {
continue
}
for j := mask; j > 0; j = (j - 1) & mask {
if g[j] != -1 {
f[i|j] = min(f[i|j], f[i]+g[j])
}
}
}
if f[1<<n-1] == inf {
return -1
}
return f[1<<n-1]
}
# Accepted solution for LeetCode #1681: Minimum Incompatibility
class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
n = len(nums)
m = n // k
g = [-1] * (1 << n)
for i in range(1, 1 << n):
if i.bit_count() != m:
continue
s = set()
mi, mx = 20, 0
for j, x in enumerate(nums):
if i >> j & 1:
if x in s:
break
s.add(x)
mi = min(mi, x)
mx = max(mx, x)
if len(s) == m:
g[i] = mx - mi
f = [inf] * (1 << n)
f[0] = 0
for i in range(1 << n):
if f[i] == inf:
continue
s = set()
mask = 0
for j, x in enumerate(nums):
if (i >> j & 1) == 0 and x not in s:
s.add(x)
mask |= 1 << j
if len(s) < m:
continue
j = mask
while j:
if g[j] != -1:
f[i | j] = min(f[i | j], f[i] + g[j])
j = (j - 1) & mask
return f[-1] if f[-1] != inf else -1
// Accepted solution for LeetCode #1681: Minimum Incompatibility
struct Solution;
use std::collections::HashSet;
impl Solution {
fn minimum_incompatibility(nums: Vec<i32>, k: i32) -> i32 {
let k = k as usize;
let n = nums.len();
let mut sets: Vec<(u32, i32)> = vec![];
let mut visited: HashSet<i32> = HashSet::new();
Self::dfs(0, n / k, 0, &mut visited, &mut sets, &nums, n);
let mut memo: Vec<Option<Option<i32>>> = vec![None; 1 << n];
if let Some(sum) = Self::dp((1 << n) - 1, &mut memo, &sets, &nums, n, k) {
sum
} else {
-1
}
}
fn dp(
cur: u32,
memo: &mut Vec<Option<Option<i32>>>,
sets: &[(u32, i32)],
nums: &[i32],
n: usize,
k: usize,
) -> Option<i32> {
if cur == 0 {
Some(0)
} else {
if let Some(res) = memo[cur as usize] {
res
} else {
let mut min_sum = std::i32::MAX;
for (set, incompatibility) in sets {
if (set & cur).count_ones() as usize == n / k {
if let Some(sum) = Self::dp(cur & !set, memo, sets, nums, n, k) {
min_sum = min_sum.min(incompatibility + sum);
}
}
}
let res = if min_sum == std::i32::MAX {
None
} else {
Some(min_sum)
};
memo[cur as usize] = Some(res);
res
}
}
}
fn dfs(
start: usize,
size: usize,
cur: u32,
visited: &mut HashSet<i32>,
all: &mut Vec<(u32, i32)>,
nums: &[i32],
n: usize,
) {
if size == 0 {
all.push((
cur,
visited.iter().max().unwrap() - visited.iter().min().unwrap(),
));
} else {
for i in start..n {
if visited.insert(nums[i]) {
Self::dfs(i + 1, size - 1, cur | 1 << i, visited, all, nums, n);
visited.remove(&nums[i]);
}
}
}
}
}
#[test]
fn test() {
let nums = vec![1, 2, 1, 4];
let k = 2;
let res = 4;
assert_eq!(Solution::minimum_incompatibility(nums, k), res);
let nums = vec![6, 3, 8, 1, 3, 1, 2, 2];
let k = 4;
let res = 6;
assert_eq!(Solution::minimum_incompatibility(nums, k), res);
let nums = vec![5, 3, 3, 6, 3, 3];
let k = 3;
let res = -1;
assert_eq!(Solution::minimum_incompatibility(nums, k), res);
let nums = vec![14, 4, 6, 6, 4, 14, 13, 12, 3, 1, 7, 14, 3, 10, 5];
let k = 1;
let res = -1;
assert_eq!(Solution::minimum_incompatibility(nums, k), res);
}
// Accepted solution for LeetCode #1681: Minimum Incompatibility
function minimumIncompatibility(nums: number[], k: number): number {
const n = nums.length;
const m = Math.floor(n / k);
const g: number[] = Array(1 << n).fill(-1);
for (let i = 1; i < 1 << n; ++i) {
if (bitCount(i) !== m) {
continue;
}
const s: Set<number> = new Set();
let [mi, mx] = [20, 0];
for (let j = 0; j < n; ++j) {
if ((i >> j) & 1) {
if (s.has(nums[j])) {
break;
}
s.add(nums[j]);
mi = Math.min(mi, nums[j]);
mx = Math.max(mx, nums[j]);
}
}
if (s.size === m) {
g[i] = mx - mi;
}
}
const inf = 1e9;
const f: number[] = Array(1 << n).fill(inf);
f[0] = 0;
for (let i = 0; i < 1 << n; ++i) {
if (f[i] === inf) {
continue;
}
const s: Set<number> = new Set();
let mask = 0;
for (let j = 0; j < n; ++j) {
if (((i >> j) & 1) === 0 && !s.has(nums[j])) {
s.add(nums[j]);
mask |= 1 << j;
}
}
if (s.size < m) {
continue;
}
for (let j = mask; j; j = (j - 1) & mask) {
if (g[j] !== -1) {
f[i | j] = Math.min(f[i | j], f[i] + g[j]);
}
}
}
return f[(1 << n) - 1] === inf ? -1 : f[(1 << n) - 1];
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.