Check for Subarray in the original array with 0 sum JavaScript

We are required to write a JavaScript function that takes in an array of Numbers with some positive and negative values. We are required to determine whether there exists a subarray in the original array whose net sum is 0 or not.

Our function should return a boolean on this basis.

Approach

The approach here is simple. We iterate over the array using a for loop, calculate the cumulative sum up to that particular element. And if any point the cumulative becomes 0 or attains a value it has previously attained, then there exists a subarray with sum 0. Otherwise there exists no subarray with sum 0.

Therefore, let's write the code for this function ?

Example

const arr = [4, 2, -1, 5, -2, -1, -2, -1, 4, -1, 5, -2, 3];
const zeroSum = arr => {
    const map = new Map();
    let sum = 0;
    for(let i = 0; i < arr.length; i++){
        sum += arr[i];
        if(sum === 0 || map.get(sum)){
            return true;
        };
        map.set(sum, i);
    };
    return false;
};
console.log(zeroSum(arr));

Output

The output in the console will be ?

true

How It Works

The algorithm uses prefix sum and a Map to track cumulative sums:

const arr = [2, -1, 3, -2];
const zeroSum = arr => {
    const map = new Map();
    let sum = 0;
    console.log("Starting check for subarray with sum 0");
    
    for(let i = 0; i < arr.length; i++){
        sum += arr[i];
        console.log(`Index ${i}, element: ${arr[i]}, cumulative sum: ${sum}`);
        
        if(sum === 0 || map.get(sum)){
            console.log("Found zero-sum subarray!");
            return true;
        };
        map.set(sum, i);
    };
    return false;
};

console.log("Result:", zeroSum(arr));
Starting check for subarray with sum 0
Index 0, element: 2, cumulative sum: 2
Index 1, element: -1, cumulative sum: 1
Index 2, element: 3, cumulative sum: 4
Index 3, element: -2, cumulative sum: 2
Found zero-sum subarray!
Result: true

Key Points

The algorithm works because:

  • If cumulative sum becomes 0, subarray from start to current index has sum 0
  • If we see the same cumulative sum twice, the subarray between those positions has sum 0
  • Time complexity: O(n), Space complexity: O(n)

Testing Different Cases

// Test cases
const test1 = [1, 2, 3];        // No zero sum
const test2 = [1, -1, 2];       // Zero sum exists
const test3 = [-1, 1, 0];       // Zero element
const test4 = [0];              // Single zero

console.log("Test 1 (no zero sum):", zeroSum(test1));
console.log("Test 2 (has zero sum):", zeroSum(test2));
console.log("Test 3 (contains zero):", zeroSum(test3));
console.log("Test 4 (single zero):", zeroSum(test4));
Test 1 (no zero sum): false
Test 2 (has zero sum): true
Test 3 (contains zero): true
Test 4 (single zero): true

Conclusion

The prefix sum approach efficiently detects zero-sum subarrays in O(n) time. The key insight is that duplicate cumulative sums indicate a zero-sum subarray between those positions.

Updated on: 2026-03-15T23:18:59+05:30

501 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements