Given an integer array, check if it contains a subarray having zero-sum.

For example,

Input:  { 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 }
 
Output: Subarray with zero-sum exists
 
The subarrays with a sum of 0 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

 
We can easily solve this problem in linear time by using hashing. The idea is to use a set to check if a subarray with zero-sum is present in the given array or not. Traverse the array and maintain the sum of elements seen so far. If the sum is seen before (i.e., the sum exists in the set), return true as there exists at least one subarray with zero-sum that ends at the current index; otherwise, insert the sum into the set.

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

C++


Download  Run Code

Output:

Subarray exists

Java


Download  Run Code

Output:

Subarray exists

Python


Download  Run Code

Output:

Subarray exists

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the input.

 
Also See:

Print all subarrays with 0 sum

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