Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Check multiple arrays for zero sum subquence

I would like to check multiple arrays if their sum is equal to zero and if yes, output yes. But only the first array is being read by the code.

There should be 3 outputs of (true or false) but I'm getting only 1 output instead

const arr0 = [3];
const arr1 = [4];
const arr2 = [2, 8, -9, 1];    

const arr = [arr0, arr1, arr2];

const zeroSum = arr => {
   const map = new Map();
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      sum += arr[i];
      if(sum === 0 || map.get(sum)){
         return true;
      };
      map.set(sum, i);
   };
   return false;
};
console.log(zeroSum(arr));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. As I mentioned in my comment arr[i] will always be an array. Trying to add that to sum will result in a string. You'll never get the result you want. To sum the elements of each array you need an inner loop to go over each element and add those to sum instead.

  2. Currently you're only returning one thing: true or false. It sounds like you want an array into which you add the results of each sum, and then you can return that.

  3. Not sure what you're using Map for so I've removed it from my example.

const arr0 = [3];
const arr1 = [4];
const arr2 = [0];
const arr3 = [2, 8, -9, 1];    

const arr = [arr0, arr1, arr2, arr3];

function zeroSum(arr) {

  // Create an output array
  const out = [];

  // Loop over the arrays
  for (let i = 0; i < arr.length; i++) {

    // Reset the sum for each iteration
    let sum = 0;
    const inner = arr[i];

    // Loop over the elements of each array
    for (let j = 0; j < inner.length; j++) {

     // Add the elements to `sum`
     sum += inner[j];
    }

    // Push either true or false to
    // the output array depending on the
    // result of the condition
    if (sum === 0) {
      out.push(true);
    } else {
      out.push(false);
    }
  }

  // Finally return the array
  return out;
}

console.log(zeroSum(arr));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!