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

2 Answers

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

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

let hasZeroSum: boolean = 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: number[]) {
    let set = new Set();
    set.add(0);
    let sum: number = 0;
    const size: number = arr.length;
      
    for (let i: number = 0; i < size; i++) {
        sum += arr[i];
        if (set.has(sum)) {
            return true;
        }
        set.add(sum);
    }
    return false;
}
 
const arr: number[] = [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
...