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

C++Server Side ProgrammingProgramming

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,

Input-1

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

Output

4

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

Input-2

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

Output

0

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.

## Example

Live Demo

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

## Output

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

5

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

Published on 05-Feb-2021 07:27:00