Find if there is a subarray with 0 sum in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n consisting of integer values. Our task is to find if there is a subarray with 0 sum. 

We need to check whether the given array contains a sub-array in which the sum of all elements is equal to 0.

Let’s take an example to understand the problem,

Input: arr[] = {3, 1, -2, 1, 4, 5}

Output: Yes


Subarray {1, -2, 1} has the sum of all values equal to 0.

Solution Approach: 

A simple solution to the problem by considering all subarrays and checking the sum of all elements is equal to 0.

Another solution to the problem is by using hashing. We need to loop over the array and then find the sum till the current index and store it in the hash table.
Then check in the hash table, if the sum value is the same as encountered previously a subarray with sum = 0 is found.

If subarray is found return True 

Else return False

Program to illustrate the working of our problem, 


Live Demo

#include <bits/stdc++.h>
using namespace std;

bool isSubArraySumZero(int arr[], int n) {
   unordered_set<int> sumHash;

   int currSum = 0;
   for (int i = 0 ; i < n ; i++) {
      currSum += arr[i];
      if (currSum == 0 || sumHash.find(currSum) != sumHash.end())
         return true;
   return false;

int main() {
   int arr[] = { 3, 1, -2, 1, 4, 5 };
   int n = sizeof(arr)/sizeof(arr[0]);
   if (isSubArraySumZero(arr, n))
      cout<<"SubArray with sum equal to 0 exists in the array";
      cout<<"No subarray exists";
   return 0;


SubArray with sum equal to 0 exists in the array
Updated on 22-Jan-2021 14:05:59