Given an array of integers, find the length of the longest sub-array with sum equals to 0.
Examples :
Input: arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
Output: 5
Explanation: The longest sub-array with
elements summing up-to 0 is {-2, 2, -8, 1, 7}
Input: arr[] = {1, 2, 3}
Output: 0
Explanation:There is no subarray with 0 sum
Input: arr[] = {1, 0, 3}
Output: 1
Explanation: The longest sub-array with
elements summing up-to 0 is {0}
Naive Approach: This involves the use of brute force where two nested loops are used. The outer loop is used to fix the starting position of the sub array, and the inner loop is used for the ending position of the sub-array and if the sum of elements is equal to zero then increase the count.
-
Algorithm:
- Consider all sub-arrays one by one and check the sum of every sub-array.
- Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i.
-
Implementation:
C/C++
/* A simple C++ program to find largest subarray with 0 sum */#include <bits/stdc++.h>usingnamespacestd;// Returns length of the largest subarray with 0 sumintmaxLen(intarr[],intn){intmax_len = 0;// Initialize result// Pick a starting pointfor(inti = 0; i < n; i++) {// Initialize currr_sum for every starting pointintcurr_sum = 0;// try all subarrays starting with 'i'for(intj = i; j < n; j++) {curr_sum += arr[j];// If curr_sum becomes 0, then update max_len// if requiredif(curr_sum == 0)max_len = max(max_len, j - i + 1);}}returnmax_len;}// Driver program to test above functionintmain(){intarr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);cout <<"Length of the longest 0 sum subarray is "<< maxLen(arr, n);return0;}chevron_rightfilter_noneJava
// Java code to find the largest subarray// with 0 sumclassGFG {// Returns length of the largest subarray// with 0 sumstaticintmaxLen(intarr[],intn){intmax_len =0;// Pick a starting pointfor(inti =0; i < n; i++) {// Initialize curr_sum for every// starting pointintcurr_sum =0;// try all subarrays starting with 'i'for(intj = i; j < n; j++) {curr_sum += arr[j];// If curr_sum becomes 0, then update// max_lenif(curr_sum ==0)max_len = Math.max(max_len, j - i +1);}}returnmax_len;}publicstaticvoidmain(String args[]){intarr[] = {15, -2,2, -8,1,7,10,23};intn = arr.length;System.out.println("Length of the longest 0 sum "+"subarray is "+ maxLen(arr, n));}}// This code is contributed by Kamal Rawalchevron_rightfilter_nonePython
# Python program to find the length of largest subarray with 0 sum# returns the lengthdefmaxLen(arr):# initialize resultmax_len=0# pick a starting pointforiinrange(len(arr)):# initialize sum for every starting pointcurr_sum=0# try all subarrays starting with 'i'forjinrange(i,len(arr)):curr_sum+=arr[j]# if curr_sum becomes 0, then update max_lenifcurr_sum==0:max_len=max(max_len, j-i+1)returnmax_len# test arrayarr=[15,-2,2,-8,1,7,10,13]print"Length of the longest 0 sum subarray is % d"%maxLen(arr)chevron_rightfilter_noneC#
// C# code to find the largest// subarray with 0 sumusingSystem;classGFG {// Returns length of the// largest subarray with 0 sumstaticintmaxLen(int[] arr,intn){intmax_len = 0;// Pick a starting pointfor(inti = 0; i < n; i++) {// Initialize curr_sum// for every starting pointintcurr_sum = 0;// try all subarrays// starting with 'i'for(intj = i; j < n; j++) {curr_sum += arr[j];// If curr_sum becomes 0,// then update max_lenif(curr_sum == 0)max_len = Math.Max(max_len,j - i + 1);}}returnmax_len;}// Driver codestaticpublicvoidMain(){int[] arr = { 15, -2, 2, -8,1, 7, 10, 23 };intn = arr.Length;Console.WriteLine("Length of the longest 0 sum "+"subarray is "+ maxLen(arr, n));}}// This code is contributed by ajitchevron_rightfilter_nonePHP
<?php// A simple PHP program to find// largest subarray with 0 sum// Returns length of the// largest subarray with 0 sumfunctionmaxLen($arr,$n){$max_len= 0;// Initialize result// Pick a starting pointfor($i= 0;$i<$n;$i++){// Initialize currr_sum// for every starting point$curr_sum= 0;// try all subarrays// starting with 'i'for($j=$i;$j<$n;$j++){$curr_sum+=$arr[$j];// If curr_sum becomes 0,// then update max_len// if requiredif($curr_sum== 0)$max_len= max($max_len,$j-$i+ 1);}}return$max_len;}// Driver Code$arr=array(15, -2, 2, -8,1, 7, 10, 23);$n= sizeof($arr);echo"Length of the longest 0 "."sum subarray is ",maxLen($arr,$n);// This code is contributed by aj_36?>chevron_rightfilter_none
Output:
Length of the longest 0 sum subarray is 5
Complexity Analysis:
- Time Complexity: O(n^2) due to the use of nested loops.
- Space complexity: O(1) as no extra space is used.
Efficient Approach: The brute force solution is calculating the sum of each and every sub-array and checking whether the sum is zero or not. Let’s now try to improve the time complexity by taking an extra space of ‘n’ length. The new array will store the sum of all the elements up to that index. The sum-index pair will be stored in a hash-map. A Hash map allows insertion and deletion of key-value pair in constant time. Therefore, the time complexity remains unaffected. So, if the same value appears twice in the array, it will be guaranteed that the particular array will be a zero-sum sub-array.
-
Mathematical Proof:
prefix(i) = arr[0] + arr[1] +…+ arr[i]
prefix(j) = arr[0] + arr[1] +…+ arr[j], j>i
ifprefix(i) == prefix(j) then prefix(j) – prefix(i) = 0 that means arr[i+1] + .. + arr[j] = 0, So a sub-array has zero sum , and the length of that sub-array is j-i+1 - Algorithm:
- Create a extra space, an array of length n (prefix), a variable (sum) , length (max_len) and a hash map (hm) to store sum-index pair as a key-value pair
- Move along the input array from starting to the end
- For every index update the value of sum = sum + array[i]
- Check for every index, if the current sum is present in the hash map or not
- If present update the value of max_len to maximum of difference of two indices (current index and index in the hash-map) and max_len
- Else Put the value (sum) in the hash map, with the index as a key-value pair.
- Print the maximum length (max_len)
- Below is a dry run of the above approach:
-
Implementation:
C++
// C++ program to find the length of largest subarray// with 0 sum#include <bits/stdc++.h>usingnamespacestd;// Returns Length of the required subarrayintmaxLen(intarr[],intn){// Map to store the previous sumsunordered_map<int,int> presum;intsum = 0;// Initialize the sum of elementsintmax_len = 0;// Initialize result// Traverse through the given arrayfor(inti = 0; i < n; i++) {// Add current element to sumsum += arr[i];if(arr[i] == 0 && max_len == 0)max_len = 1;if(sum == 0)max_len = i + 1;// Look for this sum in Hash tableif(presum.find(sum) != presum.end()) {// If this sum is seen before, then update max_lenmax_len = max(max_len, i - presum[sum]);}else{// Else insert this sum with index in hash tablepresum[sum] = i;}}returnmax_len;}// Driver Codeintmain(){intarr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };intn =sizeof(arr) /sizeof(arr[0]);cout <<"Length of the longest 0 sum subarray is "<< maxLen(arr, n);return0;}chevron_rightfilter_noneJava
// A Java program to find maximum length subarray with 0 sumimportjava.util.HashMap;classMaxLenZeroSumSub {// Returns length of the maximum length subarray with 0 sumstaticintmaxLen(intarr[]){// Creates an empty hashMap hMHashMap<Integer, Integer> hM =newHashMap<Integer, Integer>();intsum =0;// Initialize sum of elementsintmax_len =0;// Initialize result// Traverse through the given arrayfor(inti =0; i < arr.length; i++) {// Add current element to sumsum += arr[i];if(arr[i] ==0&& max_len ==0)max_len =1;if(sum ==0)max_len = i +1;// Look this sum in hash tableInteger prev_i = hM.get(sum);// If this sum is seen before, then update max_len// if requiredif(prev_i !=null)max_len = Math.max(max_len, i - prev_i);else// Else put this sum in hash tablehM.put(sum, i);}returnmax_len;}// Drive methodpublicstaticvoidmain(String arg[]){intarr[] = {15, -2,2, -8,1,7,10,23};System.out.println("Length of the longest 0 sum subarray is "+ maxLen(arr));}}chevron_rightfilter_nonePython
# A python program to find maximum length subarray# with 0 sum in o(n) time# Returns the maximum lengthdefmaxLen(arr):# NOTE: Dictonary in python in implemented as Hash Maps# Create an empty hash map (dictionary)hash_map={}# Initialize resultmax_len=0# Initialize sum of elementscurr_sum=0# Traverse through the given arrayforiinrange(len(arr)):# Add the current element to the sumcurr_sum+=arr[i]ifarr[i]is0andmax_lenis0:max_len=1ifcurr_sumis0:max_len=i+1# NOTE: 'in' operation in dictionary to search# key takes O(1). Look if current sum is seen# beforeifcurr_suminhash_map:max_len=max(max_len, i-hash_map[curr_sum] )else:# else put this sum in dictionaryhash_map[curr_sum]=ireturnmax_len# test arrayarr=[15,-2,2,-8,1,7,10,13]print"Length of the longest 0 sum subarray is % d"%maxLen(arr)chevron_rightfilter_noneC#
// C# program to find maximum// length subarray with 0 sumusingSystem;usingSystem.Collections.Generic;publicclassMaxLenZeroSumSub {// Returns length of the maximum// length subarray with 0 sumstaticintmaxLen(int[] arr){// Creates an empty hashMap hMDictionary<int,int> hM =newDictionary<int,int>();intsum = 0;// Initialize sum of elementsintmax_len = 0;// Initialize result// Traverse through the given arrayfor(inti = 0; i < arr.GetLength(0); i++) {// Add current element to sumsum += arr[i];if(arr[i] == 0 && max_len == 0)max_len = 1;if(sum == 0)max_len = i + 1;// Look this sum in hash tableintprev_i = 0;if(hM.ContainsKey(sum)) {prev_i = hM[sum];}// If this sum is seen before, then update max_len// if requiredif(hM.ContainsKey(sum))max_len = Math.Max(max_len, i - prev_i);else{// Else put this sum in hash tableif(hM.ContainsKey(sum))hM.Remove(sum);hM.Add(sum, i);}}returnmax_len;}// Driver codepublicstaticvoidMain(){int[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 };Console.WriteLine("Length of the longest 0 sum subarray is "+ maxLen(arr));}}/* This code contributed by PrinciRaj1992 */chevron_rightfilter_noneOutput:
Length of the longest 0 sum subarray is 5
- Complexity Analysis:
- Time Complexity: O(n), as use of good hashing function will allow insertion and retrieval operations in O(1) time.
- Space Complexity: O(n), for the use of extra space to store the prefix array and hashmap.
- Find the length of largest subarray in which all elements are Autobiographical Numbers
- Length of the largest subarray with contiguous elements | Set 2
- Length of the largest subarray with contiguous elements | Set 1
- Length of largest subarray whose all elements are Perfect Number
- Length of largest subarray whose all elements Powerful number
- Find subarray of Length K with Maximum Peak
- Find maximum average subarray of k length
- Find the length of the longest subarray with atmost K occurrences of the integer X
- Find length of the largest region in Boolean Matrix
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
- Maximum length of subarray such that all elements are equal in the subarray
- Length of longest subarray of length at least 2 with maximum GCD
- Maximum length of subarray such that sum of the subarray is even
- Largest subarray with GCD one
- K-th Largest Sum Contiguous Subarray
- Largest subarray having sum greater than k
- Largest Sum Contiguous Subarray
- Largest sum subarray with at-least k numbers
- Largest product of a subarray of size k
- Largest subarray with equal number of 0s and 1s
This article is contributed by Rahul Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

