Given an integer array, print all subarrays with zero-sum.

For example,

Input:  { 4, 2, -3, -1, 0, 4 }
 
Subarrays with zero-sum are
 
{ -3, -1, 0, 4 }
{ 0 }
 
 
Input:  { 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 }
 
Subarrays with zero-sum are
 
{ 3, 4, -7 }
{ 4, -7, 3 }
{ -7, 3, 1, 3 }
{ 3, 1, -4 }
{ 3, 1, 3, 1, -4, -2, -2 }
{ 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 }

Note that the problem deals with subarrays that are contiguous, i.e., whose elements occupy consecutive positions in the array.

Practice this problem

Approach 1: Using Brute-Force

A naive solution is to consider all subarrays and find their sum. If the subarray sum is equal to 0, print it. The time complexity of the naive solution is O(n3) as there are n2 subarrays in an array of size n, and it takes O(n) time to find the sum of its elements. We can optimize the method to run in O(n2) time by calculating the subarray sum in constant time.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

Subarray [0…2]
Subarray [0…9]
Subarray [1…3]
Subarray [2…5]
Subarray [3…9]
Subarray [5…7]

Java


Download  Run Code

Output:

Subarray [0…2]
Subarray [0…9]
Subarray [1…3]
Subarray [2…5]
Subarray [3…9]
Subarray [5…7]

Python


Download  Run Code

Output:

Sublist (0, 2)
Sublist (0, 9)
Sublist (1, 3)
Sublist (2, 5)
Sublist (3, 9)
Sublist (5, 7)

Approach 2: Using multimap to print all subarrays

We can use multimap to print all subarrays with a zero-sum present in the given array. The idea is to create an empty multimap to store all subarrays’ ending index having a given sum. Traverse the array and maintain the sum of elements seen so far. If the sum is seen before, at least one subarray has zero-sum, which ends at the current index. Finally, print all such subarrays.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Subarray [0…2]
Subarray [1…3]
Subarray [2…5]
Subarray [5…7]
Subarray [3…9]
Subarray [0…9]

Java


Download  Run Code

Output:

Subarray [0…2]
Subarray [1…3]
Subarray [2…5]
Subarray [5…7]
Subarray [3…9]
Subarray [0…9]

Python


Download  Run Code

Output:

Sublist is (0, 2)
Sublist is (1, 3)
Sublist is (2, 5)
Sublist is (5, 7)
Sublist is (0, 9)
Sublist is (3, 9)

Exercise: Extend the solution for a non-zero sum of the subarray

 
Related Post:

Check if a subarray with 0 sum exists or not