JavaScript program to find if there is a subarray with 0 sum

A subarray with a sum of 0 is a sequence of contiguous elements within an array where the sum of all elements in that sequence equals zero. Identifying such subarrays is a common problem in data analysis and coding challenges. The prefix sum technique efficiently solves this problem. In this article we will find if there is a subarray with 0 sum using JavaScript.

The key insight is to use prefix sums (cumulative sums) along with a data structure to track previously seen sums:

  • Continuously calculate the prefix sum while traversing the array and use a hash map to store sums seen so far.
  • Check if the current prefix sum already exists in the hash map?if it does, a subarray with zero-sum is found.
  • If the sum is not in the hash map, add it and continue until the end of the array.

How It Works

If we have seen the same prefix sum at two different positions, it means the subarray between these positions has a sum of zero. Additionally, if any prefix sum equals zero, the subarray from the beginning has zero sum.

Array: [4, 2, -3, 1, 6] Prefix sums: [4, 6, 3, 4, 10] 4 sum=4 2 sum=6 -3 sum=3 1 sum=4 6 sum=10 Sum 4 appears at index 0 and 3 Subarray [2, -3, 1] has zero sum

Approaches to find if there is a subarray with 0 sum

Following are the approaches to find if there is a subarray with 0 sum:

Using Map() method

A Map is used to store the prefix sums encountered so far along with their corresponding indices in the array. This allows us to quickly check if a prefix sum has appeared before.

Methods used in the code:

set(key, value)

The set(key, value) method stores the prefix sum as the key and the current index as its value. We use it to record the prefix sums encountered so far along with their indices for quick lookup.

has(key)

The has(key) method checks if the current prefix sum already exists in the map. We use it to detect if a subarray with a sum of 0 exists, as a repeated prefix sum indicates such a subarray.

Example

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

function hasZeroSumSubarray(arr) {
    // Create a map to store prefix sums and their indices
    let prefixSumMap = new Map();
    let prefixSum = 0;

    for (let i = 0; i < arr.length; i++) {
        // Add the current element to the prefix sum
        prefixSum += arr[i];

        // Check if the prefix sum is 0 or already exists in the map
        // Or if the current element is 0
        if (prefixSum === 0 || prefixSumMap.has(prefixSum) || arr[i] === 0) {
            return true;
        }

        // Add the prefix sum and index to the map
        prefixSumMap.set(prefixSum, i);
    }

    return false;
}

const arr = [4, 2, -3, 1, 6];
console.log("Array:", arr);
console.log("Has zero-sum subarray?", hasZeroSumSubarray(arr)); 

const arr2 = [1, 2, 3];
console.log("\nArray:", arr2);
console.log("Has zero-sum subarray?", hasZeroSumSubarray(arr2)); 

const arr3 = [1, -1];
console.log("\nArray:", arr3);
console.log("Has zero-sum subarray?", hasZeroSumSubarray(arr3));
Array: [4, 2, -3, 1, 6]
Has zero-sum subarray? true

Array: [1, 2, 3]
Has zero-sum subarray? false

Array: [1, -1]
Has zero-sum subarray? true

Time complexity: O(n), as we process each element once.
Space complexity: O(n), for storing prefix sums in the Map.

Using Set() method

In JavaScript, a Set is a built-in object that allows you to store unique values of any type, whether primitive or object references. It is particularly useful for ensuring no duplicate values are stored.

We are using the following methods in the given program:

add(value)

After calculating the prefix sum, it is added to the set using add(value) method. This stores the prefix sums encountered so far for quick lookup and ensures no duplicates are stored.

has(value)

Before adding the prefix sum, we use has(value) method to check if the current prefix sum already exists in the set. This detects if a subarray with a sum of 0 exists, as a repeated prefix sum indicates such a subarray.

Example

Here is a complete example using Set to find if there is a subarray with 0 sum:

function hasZeroSum(arr) {
    let sum = 0;
    let set = new Set();
    
    // Add 0 to handle cases where prefix sum itself is 0
    set.add(0);
     
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
        
        // If current sum already exists, zero-sum subarray found
        if (set.has(sum)) {
            return true;
        }
        
        set.add(sum);
    }
    
    return false;
}

const arr1 = [4, 2, -3, 1, 6];
console.log("Array:", arr1);
console.log("Has zero-sum subarray?", hasZeroSum(arr1));

const arr2 = [1, 2, 3];
console.log("\nArray:", arr2);
console.log("Has zero-sum subarray?", hasZeroSum(arr2));

const arr3 = [-3, 2, 3, 1, 6];
console.log("\nArray:", arr3);
console.log("Has zero-sum subarray?", hasZeroSum(arr3));
Array: [4, 2, -3, 1, 6]
Has zero-sum subarray? true

Array: [1, 2, 3]
Has zero-sum subarray? false

Array: [-3, 2, 3, 1, 6]
Has zero-sum subarray? true

Time complexity: O(n), where n is the length of the array
Space complexity: O(n) as in the worst case the set can store n elements.

Comparison

Approach Data Structure Stores Index? Use Case
Map method Map Yes When you need subarray positions
Set method Set No When you only need existence check

Conclusion

Both approaches efficiently detect zero-sum subarrays using prefix sums in O(n) time. Use Map when you need indices, or Set for simpler existence checking. The key insight is that duplicate prefix sums indicate a zero-sum subarray between those positions.

Updated on: 2026-03-15T23:19:01+05:30

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements