print all subarrays with 0 sum

Pattern: Prefix sums and difference arrays

medium

List every zero-sum subarray. For each running sum, remember all the positions where it has appeared, because each one pairs with every later repeat.

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 every contiguous subarray that adds up to 0, as a list of [start, end] index pairs (both inclusive), sorted by start and then by end. For example, [1, -1, 1, -1] gives [[0, 1], [0, 3], [1, 2], [2, 3]].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name zeroSumSubarrays, the pair format and the sort order are this guide's own.

Think first

  • In "Find if there is any subarray with sum 0", a repeated running sum meant "yes". Here, what does each repeat give you?
  • If a running sum has appeared at three earlier positions, how many zero-sum subarrays end at the current position?
  • How many pairs can there be in the worst case, for example in an array of all zeros?

Hints

    Brute force, and why it fails

    Check every subarray with a running sum and collect the zero ones: O(n²) time, already in the right order. When there are few answers the hash map version is much faster, since it only does work for real matches.

    The key insight

    Every zero-sum subarray is a pair of positions with equal running sums. Grouping positions by running sum lists all such pairs directly, with no wasted checks.

    Dry run

    10 
    -11 
    12 
    -13 
    prefix0
    ends{0: [-1]}

    nums = [1, -1, 1, -1]. For each running sum, keep the list of positions where it ended. The empty prefix (sum 0) ended at position -1.

    Step 1 of 6

    The plan

    ends = {0: [-1]}
    result = empty list
    prefix = 0
    for i from 0 to n - 1:
        prefix = prefix + nums[i]
        for e in ends[prefix]:              # empty list if new
            add [e + 1, i] to result
        append i to ends[prefix]
    sort result by start, then end
    return result
    

    Complexity

    Time
    O(n + m log m)
    Space
    O(n + m)

    m is the number of zero-sum subarrays found. The pass is O(n + m), and sorting the answers is O(m log m). In the worst case (all zeros) m is about n²/2, which no method can avoid, since that is the size of the answer.

    Edge cases

    • No zero-sum subarray: an empty list.
    • [0] gives [[0, 0]].
    • All zeros: every subarray counts, which is n(n + 1)/2 pairs.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<int[]> zeroSumSubarrays(int[] nums) {
            Map<Long, List<Integer>> ends = new HashMap<>();   // prefix sum -> indexes where that prefix ended
            ends.computeIfAbsent(0L, key -> new ArrayList<>()).add(-1);   // the empty prefix
            List<int[]> result = new ArrayList<>();
            long prefix = 0;
            for (int i = 0; i < nums.length; i++) {
                prefix += nums[i];
                List<Integer> earlier = ends.computeIfAbsent(prefix, key -> new ArrayList<>());
                for (int e : earlier) {
                    result.add(new int[]{e + 1, i});           // nums[e+1..i] sums to 0
                }
                earlier.add(i);
            }
            result.sort((p, q) -> p[0] != q[0] ? Integer.compare(p[0], q[0]) : Integer.compare(p[1], q[1]));
            return result;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> zeroSumSubarrays(vector<int>& nums) {
            unordered_map<long long, vector<int>> ends;        // prefix sum -> indexes where that prefix ended
            ends[0].push_back(-1);                             // the empty prefix
            vector<vector<int>> result;
            long long prefix = 0;
            for (int i = 0; i < static_cast<int>(nums.size()); i++) {
                prefix += nums[i];
                vector<int>& earlier = ends[prefix];
                for (int e : earlier) {
                    result.push_back({e + 1, i});              // nums[e+1..i] sums to 0
                }
                earlier.push_back(i);
            }
            sort(result.begin(), result.end());                // by start, then end
            return result;
        }
    };

    Python

    class Solution:
        def zeroSumSubarrays(self, nums):
            ends = {0: [-1]}                        # prefix sum -> indexes where that prefix ended; the empty prefix
            result = []
            prefix = 0
            for i, x in enumerate(nums):
                prefix += x
                earlier = ends.setdefault(prefix, [])
                for e in earlier:
                    result.append([e + 1, i])       # nums[e+1..i] sums to 0
                earlier.append(i)
            result.sort()                           # by start, then end
            return result

    Common mistakes

    • Keeping only one position per running sum, which finds some subarrays but not all.
    • Forgetting the empty prefix at position -1, which misses subarrays that start at index 0.
    • Reporting [e, i] instead of [e + 1, i].

    Similar problems