This runs a working implementation of O (K * 2 ^ N * N) in JavaScript. From the pseudocode https://discuss.codechef.com/questions/58420/sanskar-editorial
http://jsfiddle.net/d7q4o0nj/
function equality(set, size, count) { if(size < count) { return false; } var total = set.reduce(function(p, c) { return p + c; }, 0); if((total % count) !== 0) { return false } var subsetTotal = total / count; var search = {0: true}; var nextSearch = {}; for(var i=0; i<count; i++) { for(var bits=0; bits < (1 << size); bits++){ if(search[bits] !== true) { continue; } var sum = 0; for(var j=0; j < size; j++) { if((bits & (1 << j)) !== 0) { sum += set[j]; } } sum -= i * subsetTotal; for(var j=0; j < size; j++) { if((bits & (1 << j)) !== 0) { continue; } var testBits = bits | (1 << j); var tmpTotal = sum + set[j]; if(tmpTotal == subsetTotal) { nextSearch[testBits] = true; } else if(tmpTotal < subsetTotal) { search[testBits] = true; } } } search = nextSearch; nextSearch = {}; } if(search[(1 << size) - 1] === true) { return true; } return false; } console.log(true, equality([1,2,3,1,2,3], 6, 2)); console.log(true, equality([1, 2, 4, 5, 6], 5, 3)); console.log(true, equality([10,20,10,20,10,20,10,20,10,20], 10, 5)); console.log(false, equality([1,2,4,5,7], 5, 3));
The EDIT Algorithm finds all bitmasks (which are bits of the subset) that match the criteria (with the sum of tmpTotal less than or equal to the ideal subset of the sum of the subset). Repeating this process by the number of subsets required for counting, you either have a bitmask where all the bits of the size are set, which means success, or test failure.
Example
set = [1, 2, 1, 2]
size = 4
count = 2, we want to try to split the set into 2 subsets
subsetTotal = (1 + 2 + 1 + 2) / 2 = 3
Iteration 1:
search = {0b: true, 1b: true, 10b: true, 100b: true, 1000b: true, 101b: true}
nextSearch = {11b: true, 1100b: true, 110b: true, 1001b: true}
Iteration 2:
search = {11b: true, 1100b: true, 110b: true, 1001b: true, 111b: true, 1101b: true}
nextSearch = {1111b: true}
Final inspection
(1 <size) == 10000b, (1 <size) - 1 == 1111b
Since nextSearch [1111b] exists, we return success.