Write a program in C++ to find the length of the largest subarray with zero sum

Suppose we have given an array of N integers having the task is to find the length of the subarray having a maximum length. If there is not any subarray whose length is maximum or sum is equal to 0 then return ‘0’. For example,


N = 8
A[ ] = {15, -5, -1, 5,1, 4 }



Explanation − The largest subarray with zero-sum is { -5, -1, 5, 1} which is having a length of 4.


N = 5
A[ ] = {3, 2 ,4, 8, -1}



Explanation − Since there are no subarrays present whose sum is equal to zero, the output is ‘0’.

Approach to solve this problem

There are several approaches to solve this particular problem. The most appropriate algorithm to solve in linear time O(n) is by using a Hash Table.

The idea is to create a hash table that stores the sum of all the subarrays whose sum is stored as Key and index as Value.

We will first traverse the whole array and store the current sum. We will check if the current sum is available in the hash table or not. If it is present in the hashtable, then update the maximum length of the subarray.

  • Take Input of N size of the array.

  • A function lenMax(int *arr, int size) takes an array and its size as input which returns the maximum length of the subarray containing sum zero.

  • An unordered map of integers containing key as the sum and value as the indexes check whether any sum is repeating or not.

  • Iterating over the array element and finding the current sum of the array if the sum is present in the hashtable, then find the maximum length of the subarray. If not, then insert into the hashtable with the new sum and its index.

  • Return the maximum length as the output.


 Live Demo

using namespace std;
int lenMax(int *arr, int size){
   int sum=0;
   int maxlen=0;
   for(int i=0;i<size;i++){
      if(arr[i]==0 && maxlen==0){
      if(mp.find(sum)!= mp.end()){
         maxlen= max(maxlen, i-mp[sum]);
      } else {
   return maxlen;
int main(){
   int N=6;
   int A[N]={15,-2,2,-8,1,7,10,23};
   return 0;


If we will run the above code, it will print the output as,


The largest subarray having sum=0 is {-2, 2, -8, 1, 7}. Thus, the length of the largest subarray is ‘5’.

Updated on: 05-Feb-2021


Kickstart Your Career

Get certified by completing the course

Get Started