You get an array of positive whole numbers, nums, and a number k. Decide whether the numbers can be split into k groups that all have the same sum.
Every number must go into exactly one group, and no group may be empty. Return true if such a split exists and false if not.
Example 1
Input: nums = [5, 1, 4, 2, 3, 3], k = 3
Output: true
Why: {5, 1}, {4, 2} and {3, 3} each add up to 62 more examples and the constraints
Example 2
Input: nums = [2, 2, 3, 5], k = 2 Output: false Why: each half must be 6, and no group with the 5 makes 6
Example 3
Input: nums = [6, 3, 9], k = 3 Output: false Why: each group needs 6, but 9 alone is already more
Constraints
- 1 ≤ k ≤ length of nums ≤ 16
- 1 ≤ nums[i] ≤ 10,000
- No value appears more than 4 times
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Backtrack into k bucketsO(kⁿ)
- Bitmask DPO(n·2ⁿ)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Worst-case work for 16 numbers | Verdict |
|---|---|---|---|
| Backtrack into k buckets | O(kⁿ) | Fast with pruning; no guarantee | |
| Bitmask DP | O(n·2ⁿ) | Best; about a million steps |
n = length of nums, k = number of groups.
Edge cases to test
- Total does not divide. [1, 2, 3, 4, 5] with k = 4 has total 15: false straight away.
- A number above the target. [6, 3, 9] with k = 3 needs 6 per group, and 9 can never fit.
- k = 1. The whole array is one group: always true.
- k = n. Every number is its own group, so all of them must be equal.
Common mistakes
- Checking only that the total divides by k. [2, 2, 3, 5] with k = 2 passes that check and is still false.
- Storing the full used sum per mask instead of the fill of the open group, so a group can spill past the target.
- Backtracking without skipping equal buckets, which tries the same split k! times and times out.
How to talk through it
- 1Clarify. Must every number be used? Are all numbers positive? n is at most 16, which hints at bitmasks.
- 2Find the target. Each group sums to total / k; if that is not whole, or a number is bigger, answer false.
- 3Give the backtracking. Place numbers into buckets, largest first, and name the two pruning rules.
- 4Switch to masks. Fill groups one at a time; the used set decides the open fill, so dp over 2ⁿ masks.
- 5Test out loud. Run [2, 2, 3, 5] with k = 2 and a case with a number above the target.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?