Array thirds with equal sums in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of integers as the first and the only argument. Our function should return true if and only if we can partition the array into three non-empty parts with equal sums, false otherwise.

For example, if the input to the function is −

const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4];

Then the output should be −

const output = true;

Output Explanation

Because,

3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Example

The code for this will be −

 Live Demo

const arr = [3, 3, 6, 5, -2, 2, 5, 1, -9, 4];
const thirdSum = (arr = []) => {
   const sum = arr.reduce((acc, val) => acc + val, 0);
   if(!Number.isInteger(sum / 3)){
      return false;
   };
   let count = 0;
   let curr = 0;
   const target = sum / 3;
   for(const num of arr){
      curr += num;
      if(curr === target){
         curr = 0;
         count += 1;
      };
   };
   return count === 3 && curr === 0;
};
console.log(thirdSum(arr));

Output

And the output in the console will be −

true

Updated on: 09-Apr-2021

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements