Problem of the day
You are given an array of 'N' integers, and a positive integer 'K'. You need to determine if it is possible to divide the array into 'K' non-empty subsets such that the sum of elements of each subset is equal.
Note:
1. The array can have duplicate elements.
2. Each of the array elements must belong to exactly one of the 'K' subsets.
3. The elements chosen for a subset may not be contiguous in the array.
The first line of the input contains an integer 'T', denoting the number of test cases.
The first line of each test case will contain an integer 'N', denoting the size of the input array.
The second line of each test case will contain 'N' space-separated integers denoting the array elements.
The third and last line of each input will contain the value 'K', which denotes the number of non-empty subsets you have to break the input array into.
Output Format:
For each test case, print a single line containing “True” if it is possible to divide the array into ‘K' equal sum subsets, “False” otherwise.
The output of each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 15
0 <= NUMS[i] <= 10 ^ 3
1 <= K <= N
Where NUMS[i] denotes ith element of given array 'NUMS'.
Time Limit: 1 sec.
1
8
4 3 1 3 4 3 1 2
3
True
It's possible to divide it into 3 subsets (4, 3), (1, 3, 3), (4, 2, 1) with equal sum = 7.
1
7
5 1 2 6 7 1 2
4
False
Try all possible combinations of ‘K’ subsets.
O(K * (2 ^ N ), where ‘N’ is the number of elements in the input array and ‘K’ the number of subsets in which the array is to be divided.
As we are traversing the entire array for each subset. So for each subset, we are choosing the suitable elements from the array (basically iterate over the array and for each element either use it or drop it, which is O(2 ^ N). We are doing the same for each subset. Total subsets are ‘K’. So the overall Time Complexity will be O(K * (2 ^ N)).
O(N), where ‘N’ is the number of elements in the input array.
As, we are traversing the entire array for each subset, the height of the recursion tree would still remain O(N) as we are not calling the recursive function for already visited elements. Also, O(N) for the visited array. So the Space Complexity becomes stack size + VISITED array = O(N)+O(N) = O(N).