319. Partition to K Equal Sum Subsets

You are given an integer array nums and an integer k. Your task is to determine if it is possible to divide this array into exactly k non-empty subsets such that the sum of elements in every subset is exactly the same.

Example 1:

Input: nums = [4, 3, 2, 3, 5, 2, 1], k =4

Output: true

Explanation:

The total sum is 20, meaning each subset must sum to 5. We can divide the array into 4 subsets: (5), (1, 4), (2, 3), and (2, 3).

Example 2:

Input : nums = [1, 2, 3, 4], k = 3

Output: false

Explanation:

The total sum is 10. Since 10 is not divisible by 3, it is impossible to divide the array into 3 equal-sum subsets.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 2, 3, 4, 5, 5], k = 4

(Is it possible to partition this array into 4 subsets of equal sum?)

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= nums.length <= 16
  • 1 <= nums[i] <=104
  • The frequency of each element is in the range [ 1, 4 ].

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
bool canPartitionKSubsets(vector<int>& nums, int k) {
}
};
Test Case

Input:

K
Nums