Skip to content

Instantly share code, notes, and snippets.

@modeware
Last active August 14, 2021 17:47
Show Gist options
  • Save modeware/9f661c19dd0d89dccc56f83b70e0dd0c to your computer and use it in GitHub Desktop.
Save modeware/9f661c19dd0d89dccc56f83b70e0dd0c to your computer and use it in GitHub Desktop.
Program to find the number of subarrays in an array that have sum 0.
//Goal - To find the number of sub arrays in an array whose sum is 0
const test1 = [1,2,3, -1, -5, -3, -2, 0]
function sum0(array) {
let subarrays = {}
let count = 0;
//Iterate over the array to find subarrays corresponding to the value of i
for(let i = array.length -1 ; i >= 0; i--) {
//For example if i = 5, createNSubArray will return all subarrays of length 5
let s = createNSubArray(array, i + 1)
if(s.length > 0){
subarrays[i] = s
count+=s.length;
}
}
console.log("FINAL", subarrays)
console.log("FINAL", count)
return count
}
function createNSubArray(array, n){
// This functoon iterates returns subarrays of an array corresponding to value of n
/*if array = [1,2,3] and n=2 it will return [[1,2], [1,3], [2,3]], the time complexity is O(n^2) */
let subarrays = []
let js = 0;
let end = n - 1 ;
for(let i = 0; i < array.length; i++){
for(let j = i + n - 1; j < array.length; j++){
let slicedArray = array.slice(i, end);
slicedArray.push(array[j])
//Only add those arrays that have sum 0
if(sum(slicedArray) == 0){
subarrays.push(slicedArray);
}
js = j;
}
end++;
if(n == 1){
break;
}
}
return subarrays
}
//Returns sum of an array
function sum(array){
let sum = 0;
for(let i = 0; i < array.length; i++){
sum += array[i];
}
return sum
}
console.log(sum0(test1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment