Subarray pairs with equal sums in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the only argument.

The function should determine whether there exists any way in which we can split the array into two subarray such that the sum of the elements present in the two subarrays are equal. While dividing the elements into subarrays we have to make sure that no element from the original array is left.

For example −

If the input array is −

const arr = [5, 3, 7, 4, 1, 8, 2, 6];

Then the output should be −

const output = true;

because the desired subarrays are: [5, 3, 4, 6] and [7, 1, 8, 2] with both having sum equal to 18.

Example

Following is the code −

const arr = [5, 3, 7, 4, 1, 8, 2, 6];
const canPartition = (arr = []) => {
   const sum = arr.reduce((acc, val) => acc + val);
   if (sum % 2 !== 0){
      return false;
   };
   const target = sum / 2;
   const array = new Array(target + 1).fill(false);
   array[0] = true;
   for (const num of arr) {
      if (array[target - num]){
         return true
      };
      for (let i = target; i >= num; i--) {
         array[i] = array[i - num];
      }
   }
   return false;
};
console.log(canPartition(arr));

Output

Following is the console output −

true

Updated on: 27-Jan-2021

96 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements