Finding n subarrays with equal sum in JavaScript


We are required to write a JavaScript function that takes in an array of integers as the first argument and an integer as the second argument.

The function should check whether we can create n (second argument) subarrays from the original array such that all the subarrays have the equal sum.

For example −

If the inputs are −

const arr = [4, 3, 2, 3, 5, 2, 1];
const num = 4;

The output should be true because the subarrays are: [5], [1, 4], [2, 3], [2, 3] all having sum equal to 5.

Example

Following is the code −

const arr = [4, 3, 2, 3, 5, 2, 1];
const num = 4;
const canFormSubarray = (arr = [], num) => {
   const total = arr.reduce((sum, num) => sum + num, 0);

   if (total % num !== 0) {
      return false;
   }
   const target = total / num;
   const visited = new Array(arr.length).fill(false);
   const canPartition = (start, numberOfSubsets, currentSum) => {
      if (numberOfSubsets === 1) {
         return true;
      }
      if (currentSum === target) {
         return canPartition(0, numberOfSubsets - 1, 0);
      };
      for (let i = start; i < arr.length; i++) {
         if (!visited[i]) {
            visited[i] = true;
            if (canPartition(i + 1, numberOfSubsets, currentSum + arr[i])) {
               return true;
            }
            visited[i] = false;
         };
      };
      return false;
   };
   return canPartition(0, num, 0);
};
console.log(canFormSubarray(arr, num));

Output

Following is the console output −

true

Updated on: 18-Jan-2021

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements