JavaScript Program to Find if there is a subarray with 0 sum

We, as developers, are often asked to find if there is a subarray with 0 sum in an array. This can be done by using the concept of prefix sum. We will keep track of the sum of elements of the subarray seen so far and store it in a hash map. If the sum is seen before, it means that the subarray with this sum exists and has 0 sum. We will be continuously updating the hash map with the sum of elements seen so far. This way, we can determine if there is a subarray with 0 sum in an array.


  • Initialize variables "sum" to 0 and "hash_map" object to store the sum values as keys and their indices as values.

  • Loop through the given array, for each element −

    • Add the current element to the sum.

    • If the current sum is 0 or it is already present in the hash_map, return true as there is a subarray with 0 sum.

    • Else, insert the sum value and its index to the hash_map.

  • If loop completes, return false as there is no subarray with 0 sum.

  • The hash_map helps to keep track of the cumulative sum and determine if there is any repeating sum.

  • If the repeating sum is found, it means that there is a subarray between those two sums with a sum of 0.

  • The time complexity of this approach is O(n), where n is the number of elements in the given array.


Here is a complete example of a JavaScript program to find if there is a subarray with 0 sum −

function hasZeroSum(arr) {
   let sum = 0;
   let set = new Set();
   for (let i = 0; i < arr.length; i++) {
      sum += arr[i];
      if (set.has(sum)) return true;
   return false;
const arr = [4, 2, -3, 1, 6];


  • The function hasZeroSum takes an array arr as its argument.

  • We initialize two variables sum and set. The sum variable is used to keep track of the current sum of the elements in the subarray, and set is used to store the previously seen sums.

  • We then use a for loop to iterate through the elements of the array.

  • On each iteration, we add the current element to sum and check if set already contains the value of sum.

  • If the value of sum is already in set, it means that the subarray that starts from the first occurrence of this sum and ends at the current element has a sum of 0, so we return true.

  • If the value of sum is not in set, we add it to the set.

  • If we have iterated through the entire array and have not returned true, it means that there's no subarray with 0 sum, so we return false.

  • Finally, we test the function with an example array and log the result to the console.

Updated on: 15-Mar-2023


Kickstart Your Career

Get certified by completing the course

Get Started