Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to check if an array contains a contiguous subarray having zero-sum in JavaScript

2 Answers

0 votes
function hasZeroSumSubarray(arr) {
    const size = arr.length;
    
    for (let i = 0; i < size; i++) {
        let sum = arr[i];
        if (sum == 0) {
            return true;
        }
        for (let j = i + 1; j < size; j++) {
            sum += arr[j];
            if (sum == 0) {
                return true;
            }
        }
    }
    return false;
}

const arr = [8, 4, -5, 1, 9];

let hasZeroSum = hasZeroSumSubarray(arr);

if (hasZeroSum) {
    console.log("The array contains a contiguous subarray with zero-sum");
}
else {
    console.log("The array does not contain a contiguous subarray with zero-sum");
}



 
/*
run:
 
"The array contains a contiguous subarray with zero-sum"
 
*/

 



answered Oct 23, 2023 by avibootz
0 votes
function hasZeroSumSubarray(arr) {
    let set = new Set();
    set.add(0);
    let sum = 0;
    const size = arr.length;
      
    for (let i = 0; i < size; i++) {
        sum += arr[i];
        if (set.has(sum)) {
            return true;
        }
        set.add(sum);
    }
    return false;
}
 
const arr = [4, 3, 5, -7, -1, 8, 6, 2];
 
if (hasZeroSumSubarray(arr)) {
    console.log("Subarray exists");
} 
else {
    console.log("Subarray does not exist");
}
 
 
 
 
/*
run:
 
"Subarray exists"
 
*/

 



answered Oct 24, 2023 by avibootz
...