Find if there is any subarray with sum equal to 0

Pattern: Prefix sums and difference arrays

medium

A zero-sum subarray exists exactly when some running sum repeats, so walk once and keep a set of running sums.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of whole numbers, which may be negative. Return true if some contiguous, non-empty subarray adds up to 0, and false otherwise. For example, [4, 2, -3, 1, 6] has [2, -3, 1], so the answer is true. [1, 2, 3] has none.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name hasZeroSumSubarray is this guide's own.

Think first

  • Write the running sums of [4, 2, -3, 1, 6]. Do any two of them match?
  • If the running sum is the same at two positions, what is the sum of the elements between them?
  • Why should 0 be in the set before you start? Try [-1, 1] and [0].

Hints

    Brute force, and why it fails

    Check every subarray with a running sum: O(n²). It is correct, but slow for large arrays.

    The key insight

    A zero-sum subarray means the running sum returns to a value it already had. Detecting a repeated value is exactly what a hash set is for.

    Dry run

    40 
    21 
    -32 
    13 
    64 
    prefix0
    seen{0}

    nums = [4, 2, -3, 1, 6]. The set of running sums starts with 0, for the empty prefix.

    Step 1 of 5

    The plan

    seen = {0}
    prefix = 0
    for x in nums:
        prefix = prefix + x
        if prefix is in seen:
            return true
        add prefix to seen
    return false
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    One pass, and the set can hold up to n + 1 running sums.

    Edge cases

    • A single 0 is a zero-sum subarray: [0] returns true.
    • A 0 anywhere in the array makes the answer true, because the running sum repeats right there.
    • All positive numbers: the running sum only grows, so the answer is false.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean hasZeroSumSubarray(int[] nums) {
            Set<Long> seen = new HashSet<>();
            seen.add(0L);                                      // the empty prefix
            long prefix = 0;
            for (int x : nums) {
                prefix += x;
                if (!seen.add(prefix)) {                       // this prefix appeared before: the part between sums to 0
                    return true;
                }
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool hasZeroSumSubarray(vector<int>& nums) {
            unordered_set<long long> seen;
            seen.insert(0);                                    // the empty prefix
            long long prefix = 0;
            for (int x : nums) {
                prefix += x;
                if (seen.count(prefix)) {                      // this prefix appeared before: the part between sums to 0
                    return true;
                }
                seen.insert(prefix);
            }
            return false;
        }
    };

    Python

    class Solution:
        def hasZeroSumSubarray(self, nums):
            seen = {0}                              # the empty prefix
            prefix = 0
            for x in nums:
                prefix += x
                if prefix in seen:                  # this prefix appeared before: the part between sums to 0
                    return True
                seen.add(prefix)
            return False

    Common mistakes

    • Starting with an empty set, which misses zero-sum subarrays that begin at index 0 (such as [-1, 1]).
    • Checking only whether a running sum is 0, which misses zero-sum subarrays in the middle.

    Similar problems