Find Subarray with 0 Sum in JavaScript



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.

  • 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.

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) is used to store the prefix sum as the key and the current index as its value. In the given example we will use it to record the prefix sums encountered so far along with their indices for quick lookup.

has(key) :

The has(key) checks if the current prefix sum already exists in the map. In the example, we will 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("
Array:", arr2); console.log("Has zero-sum subarray?", hasZeroSumSubarray(arr2)); const arr3 = [1, -1]; console.log("
Array:", arr3); console.log("Has zero-sum subarray?", hasZeroSumSubarray(arr3));

Output

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 Set.

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 (sum), it is added to the set using add(value) as set.add(sum). To store the prefix sums encountered so far for quick lookup and to ensure no duplicates are stored.

has(value)

Before adding the prefix sum,we will be using has(value) as set.has(sum) in the example to check if the current prefix sum already exists in the set. 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 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;
      set.add(sum);
   }
    
   return false;
}
const arr = [4, 2, -3, 1, 6];
console.log(hasZeroSum(arr));

Output

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.

Updated on: 2024-12-02T21:46:54+05:30

504 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements