# Find the length of largest subarray with 0 sum

• Difficulty Level : Medium
• Last Updated : 28 Jun, 2022

Given an array of integers, find the length of the longest sub-array with a sum that equals 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:

1. Consider all sub-arrays one by one and check the sum of every sub-array.
2. Run two loops: the outer loop picks the starting point i and the inner loop tries all sub-arrays starting from i.

Implementation:

## C++

 `/* A simple C++ program to find ` `largest subarray with 0 sum */` `#include ` `using` `namespace` `std;`   `// Returns length of the largest` `// subarray with 0 sum` `int` `maxLen(``int` `arr[], ``int` `n)` `{` `    ``// Initialize result` `    ``int` `max_len = 0; `   `    ``// Pick a starting point` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// Initialize currr_sum for` `        ``// every starting point` `        ``int` `curr_sum = 0;`   `        ``// try all subarrays starting with 'i'` `        ``for` `(``int` `j = i; j < n; j++) {` `            ``curr_sum += arr[j];`   `            ``// If curr_sum becomes 0, ` `            ``// then update max_len` `            ``// if required` `            ``if` `(curr_sum == 0)` `                ``max_len = max(max_len, j - i + 1);` `        ``}` `    ``}` `    ``return` `max_len;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``cout << ``"Length of the longest 0 sum subarray is "` `         ``<< maxLen(arr, n);` `    ``return` `0;` `}`

## Java

 `// Java code to find the largest subarray` `// with 0 sum` `class` `GFG {` `    ``// Returns length of the largest subarray` `    ``// with 0 sum` `    ``static` `int` `maxLen(``int` `arr[], ``int` `n)` `    ``{` `        ``int` `max_len = ``0``;`   `        ``// Pick a starting point` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``// Initialize curr_sum for every` `            ``// starting point` `            ``int` `curr_sum = ``0``;`   `            ``// try all subarrays starting with 'i'` `            ``for` `(``int` `j = i; j < n; j++) {` `                ``curr_sum += arr[j];`   `                ``// If curr_sum becomes 0, then update` `                ``// max_len` `                ``if` `(curr_sum == ``0``)` `                    ``max_len = Math.max(max_len, j - i + ``1``);` `            ``}` `        ``}` `        ``return` `max_len;` `    ``}`   `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `arr[] = { ``15``, -``2``, ``2``, -``8``, ``1``, ``7``, ``10``, ``23` `};` `        ``int` `n = arr.length;` `        ``System.out.println(``"Length of the longest 0 sum "` `                           ``+ ``"subarray is "` `+ maxLen(arr, n));` `    ``}` `}` `// This code is contributed by Kamal Rawal`

## Python3

 `# Python program to find the length of largest subarray with 0 sum`   `# returns the length` `def` `maxLen(arr):` `    `  `    ``# initialize result` `    ``max_len ``=` `0`   `    ``# pick a starting point` `    ``for` `i ``in` `range``(``len``(arr)):` `        `  `        ``# initialize sum for every starting point` `        ``curr_sum ``=` `0` `        `  `        ``# try all subarrays starting with 'i'` `        ``for` `j ``in` `range``(i, ``len``(arr)):` `        `  `            ``curr_sum ``+``=` `arr[j]`   `            ``# if curr_sum becomes 0, then update max_len` `            ``if` `curr_sum ``=``=` `0``:` `                ``max_len ``=` `max``(max_len, j``-``i ``+` `1``)`   `    ``return` `max_len`     `# test array` `arr ``=` `[``15``, ``-``2``, ``2``, ``-``8``, ``1``, ``7``, ``10``, ``13``]`   `print` `(``"Length of the longest 0 sum subarray is % d"` `%` `maxLen(arr))`

## C#

 `// C# code to find the largest` `// subarray with 0 sum` `using` `System;`   `class` `GFG {` `    ``// Returns length of the` `    ``// largest subarray with 0 sum` `    ``static` `int` `maxLen(``int``[] arr, ``int` `n)` `    ``{` `        ``int` `max_len = 0;`   `        ``// Pick a starting point` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``// Initialize curr_sum` `            ``// for every starting point` `            ``int` `curr_sum = 0;`   `            ``// try all subarrays` `            ``// starting with 'i'` `            ``for` `(``int` `j = i; j < n; j++) {` `                ``curr_sum += arr[j];`   `                ``// If curr_sum becomes 0,` `                ``// then update max_len` `                ``if` `(curr_sum == 0)` `                    ``max_len = Math.Max(max_len,` `                                       ``j - i + 1);` `            ``}` `        ``}` `        ``return` `max_len;` `    ``}`   `    ``// Driver code` `    ``static` `public` `void` `Main()` `    ``{` `        ``int``[] arr = { 15, -2, 2, -8,` `                      ``1, 7, 10, 23 };` `        ``int` `n = arr.Length;` `        ``Console.WriteLine(``"Length of the longest 0 sum "` `                          ``+ ``"subarray is "` `+ maxLen(arr, n));` `    ``}` `}`   `// This code is contributed by ajit`

## PHP

 ``

## Javascript

 ``

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 + arr +…+ arr[i]
prefix(j) = arr + arr +…+ 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:

1. Create an extra space, an array of length n (prefix), a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair.
2. Move along the input array from the start to the end.
3. For every index, update the value of sum = sum + array[i].
4. Check every index, if the current sum is present in the hash map or not.
5. If present, update the value of max_len to a maximum difference of two indices (current index and index in the hash-map) and max_len.
6. Else, put the value (sum) in the hash map, with the index as a key-value pair.
7. 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 ` `using` `namespace` `std;`   `// Returns Length of the required subarray` `int` `maxLen(``int` `arr[], ``int` `n)` `{` `    ``// Map to store the previous sums` `    ``unordered_map<``int``, ``int``> presum;`   `    ``int` `sum = 0; ``// Initialize the sum of elements` `    ``int` `max_len = 0; ``// Initialize result`   `    ``// Traverse through the given array` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Add current element to sum` `        ``sum += 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 table` `        ``if` `(presum.find(sum) != presum.end()) {` `            ``// If this sum is seen before, then update max_len` `            ``max_len = max(max_len, i - presum[sum]);` `        ``}` `        ``else` `{` `            ``// Else insert this sum with index in hash table` `            ``presum[sum] = i;` `        ``}` `    ``}`   `    ``return` `max_len;` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``cout << ``"Length of the longest 0 sum subarray is "` `         ``<< maxLen(arr, n);`   `    ``return` `0;` `}`

## Java

 `// A Java program to find maximum length subarray with 0 sum` `import` `java.util.HashMap;`   `class` `MaxLenZeroSumSub {`   `    ``// Returns length of the maximum length subarray with 0 sum` `    ``static` `int` `maxLen(``int` `arr[])` `    ``{` `        ``// Creates an empty hashMap hM` `        ``HashMap hM = ``new` `HashMap();`   `        ``int` `sum = ``0``; ``// Initialize sum of elements` `        ``int` `max_len = ``0``; ``// Initialize result`   `        ``// Traverse through the given array` `        ``for` `(``int` `i = ``0``; i < arr.length; i++) {` `            ``// Add current element to sum` `            ``sum += arr[i];`   `            ``if` `(arr[i] == ``0` `&& max_len == ``0``)` `                ``max_len = ``1``;`   `            ``if` `(sum == ``0``)` `                ``max_len = i + ``1``;`   `            ``// Look this sum in hash table` `            ``Integer prev_i = hM.get(sum);`   `            ``// If this sum is seen before, then update max_len` `            ``// if required` `            ``if` `(prev_i != ``null``)` `                ``max_len = Math.max(max_len, i - prev_i);` `            ``else` `// Else put this sum in hash table` `                ``hM.put(sum, i);` `        ``}`   `        ``return` `max_len;` `    ``}`   `    ``// Drive method` `    ``public` `static` `void` `main(String arg[])` `    ``{` `        ``int` `arr[] = { ``15``, -``2``, ``2``, -``8``, ``1``, ``7``, ``10``, ``23` `};` `        ``System.out.println(``"Length of the longest 0 sum subarray is "` `                           ``+ maxLen(arr));` `    ``}` `}`

## Python3

 `# A python program to find maximum length subarray ` `# with 0 sum in o(n) time`   `# Returns the maximum length` `def` `maxLen(arr):` `    `  `    ``# NOTE: Dictionary in python in implemented as Hash Maps` `    ``# Create an empty hash map (dictionary)` `    ``hash_map ``=` `{}`   `    ``# Initialize result` `    ``max_len ``=` `0`   `    ``# Initialize sum of elements` `    ``curr_sum ``=` `0`   `    ``# Traverse through the given array` `    ``for` `i ``in` `range``(``len``(arr)):` `        `  `        ``# Add the current element to the sum` `        ``curr_sum ``+``=` `arr[i]`   `        ``if` `arr[i] ``is` `0` `and` `max_len ``is` `0``:` `            ``max_len ``=` `1`   `        ``if` `curr_sum ``is` `0``:` `            ``max_len ``=` `i ``+` `1`   `        ``# NOTE: 'in' operation in dictionary to search ` `        ``# key takes O(1). Look if current sum is seen ` `        ``# before` `        ``if` `curr_sum ``in` `hash_map:` `            ``max_len ``=` `max``(max_len, i ``-` `hash_map[curr_sum] )` `        ``else``:`   `            ``# else put this sum in dictionary` `            ``hash_map[curr_sum] ``=` `i`   `    ``return` `max_len`     `# test array` `arr ``=` `[``15``, ``-``2``, ``2``, ``-``8``, ``1``, ``7``, ``10``, ``13``]` ` `  `print` `(``"Length of the longest 0 sum subarray is % d"` `%` `maxLen(arr))`

## C#

 `// C# program to find maximum` `// length subarray with 0 sum` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `MaxLenZeroSumSub {`   `    ``// Returns length of the maximum` `    ``// length subarray with 0 sum` `    ``static` `int` `maxLen(``int``[] arr)` `    ``{` `        ``// Creates an empty hashMap hM` `        ``Dictionary<``int``, ``int``> hM = ``new` `Dictionary<``int``, ``int``>();`   `        ``int` `sum = 0; ``// Initialize sum of elements` `        ``int` `max_len = 0; ``// Initialize result`   `        ``// Traverse through the given array` `        ``for` `(``int` `i = 0; i < arr.GetLength(0); i++) {` `            ``// Add current element to sum` `            ``sum += arr[i];`   `            ``if` `(arr[i] == 0 && max_len == 0)` `                ``max_len = 1;`   `            ``if` `(sum == 0)` `                ``max_len = i + 1;`   `            ``// Look this sum in hash table` `            ``int` `prev_i = 0;` `            ``if` `(hM.ContainsKey(sum)) {` `                ``prev_i = hM[sum];` `            ``}`   `            ``// If this sum is seen before, then update max_len` `            ``// if required` `            ``if` `(hM.ContainsKey(sum))` `                ``max_len = Math.Max(max_len, i - prev_i);` `            ``else` `{` `                ``// Else put this sum in hash table` `                ``if` `(hM.ContainsKey(sum))` `                    ``hM.Remove(sum);`   `                ``hM.Add(sum, i);` `            ``}` `        ``}`   `        ``return` `max_len;` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main()` `    ``{` `        ``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 */`

## Javascript

 ``

Output

`Length of the longest 0 sum subarray is 5`

Complexity Analysis:

• Time Complexity: O(n), as use of the 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.

Alternative and efficient approach:

The above efficient approach can be tweaked a little bit to handle all if conditions in one.

Algorithm:

1. In this approach, the Hash Map will store (Cumulative Sum, index+1).
2. It starts with inserting (0,0) to the Hash Map at the beginning and initializing cumSum = 0 and length = -1;
3. Traverse throughout the array.
4. Find cumulative sum till that point by Cumulative sum = Cumulative sum + current value of array;
5. if the cumulative sum is already present in the Hash Map as a key then update length as maximum of (length, index+1 – value corresponding to cumulative sum in Hash Map)
6. else insert (cumulative sum, index + 1) to the Hash Map.

Explanation:

1. Let’s consider array [ 0, -2, 2, 2, -2].
2. initial Hash Map {0, 0}, cumSum = 0, length = -1.
3. Iterating over the array with index ranging from 0 to array length – 1.
• index = 0, cumSum = 0, cumSum is present in Hash Map as a key. length = Max(length, index+1 – hm.get(cumSum)) => length = max(-1 , 1) = 1
• index = 1, cumSum = -2, cumSum is not present in Hash Map as a key. Inserting (cumSum, index + 1). Hash Map becomes { 0 = 0, -2 = 2}
• index = 2, cumSum = 0, cumSum is present in Hash Map as a key. So, length = Max(1 ,  2+1-0). Hence, length = 3.
• index = 3, cumSum = 2, cumSum is not present in Hash Map key. Hash Map = { 0 = 0, -2 = 2, 2 = 4}
• index = 4, cumSum = 0, cumSum is present as a key, length = max(3 , 4+1-0) = 5

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// to find maximum length of sub array having sum 0` `int` `maxSubArrayLen(vector<``int``>arr){` `        `  `    ``map<``int``,``int``>hm;` `    ``hm = 0;` `    ``int` `length = -1;` `    ``int` `cumSum = 0;`   `    ``for` `(``int` `i = 0; i < arr.size(); i++) {` `        ``cumSum = cumSum + arr[i];`   `        ``if` `(hm.find(cumSum) != hm.end()) {` `            ``length = max(length,` `                  ``i + 1 - hm[cumSum]);` `        ``}` `        ``else` `{` `            ``hm[cumSum] = i + 1;` `        ``}` `    ``}` `    ``return` `length;` `}`     `// Driver Code` `int` `main(){`   `vector<``int``>arr = {15, -2, 2, -8, 1, 7, 10, 23};` `cout<

## Java

 `// to find maximum length of sub array having sum 0` `import` `java.io.*;` `import` `java.util.HashMap;`   `class` `GFG {` `    ``public` `static` `int` `maxSubArrayLen(``int``[] arr)` `    ``{` `        ``HashMap hm = ``new` `HashMap<>();` `        ``hm.put(``0``, ``0``);` `        ``int` `length = -``1``;` `        ``int` `cumSum = ``0``;`   `        ``for` `(``int` `i = ``0``; i < arr.length; i++) {` `            ``cumSum = cumSum + arr[i];`   `            ``if` `(hm.containsKey(cumSum)) {` `                ``length = Math.max(length,` `                                  ``i + ``1` `- hm.get(cumSum));` `            ``}` `            ``else` `{` `                ``hm.put(cumSum, i + ``1``);` `            ``}` `        ``}` `        ``return` `length;` `    ``}` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] arr` `            ``= ``new` `int``[] { ``15``, -``2``, ``2``, -``8``, ``1``, ``7``, ``10``, ``23` `};` `        ``System.out.println(maxSubArrayLen(arr));` `    ``}` `}` `// Contributed by Bibhu Parambrahma Patra (bibhup)`

## Python3

 `# to find maximum length of sub array having sum 0` `def` `maxSubArrayLen(arr):    ` `    ``hm ``=` `{}` `    ``hm[``0``] ``=` `0` `    ``length ``=` `-``1` `    ``cumSum ``=` `0`   `    ``for` `i ``in` `range``(``len``(arr)):` `        ``cumSum ``=` `cumSum ``+` `arr[i]`   `        ``if` `(cumSum ``in` `hm):` `            ``length ``=` `max``(length,i ``+` `1` `-` `hm[cumSum])` `        ``else``:` `            ``hm[cumSum] ``=` `i ``+` `1`   `    ``return` `length`   `# driver code` `arr ``=` `[``15``, ``-``2``, ``2``, ``-``8``, ``1``, ``7``, ``10``, ``23``]` `print``(maxSubArrayLen(arr))`   `# This code is contributed by shinjanpatra`

## C#

 `// C# program to find maximum length of sub array having sum` `// 0` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG` `{`   `  ``// function to find the length of the longest` `  ``// of the sub array with its sum equal to 0` `  ``static` `int` `maxSubArrayLen(``int``[] arr)` `  ``{`   `    ``// declaring a dictionary to maintain the length and` `    ``// sum of each subarray` `    ``IDictionary<``int``, ``int``> hm` `      ``= ``new` `Dictionary<``int``, ``int``>();` `    ``hm = 0;` `    ``int` `length = -1;` `    ``int` `cumSum = 0;`   `    ``// iterating over the array and building the` `    ``// dictionary` `    ``for` `(``int` `i = 0; i < arr.Length; i++) {` `      ``cumSum = cumSum + arr[i];`   `      ``if` `(hm.ContainsKey(cumSum)) {` `        ``length` `          ``= Math.Max(length, i + 1 - hm[cumSum]);` `      ``}` `      ``else` `{` `        ``hm[cumSum] = i + 1;` `      ``}` `    ``}` `    ``return` `length;` `  ``}`   `  ``// driver call` `  ``public` `static` `void` `Main(``string``[] args)` `  ``{` `    ``int``[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 };`   `    ``// function call` `    ``Console.WriteLine(maxSubArrayLen(arr));` `  ``}` `}`   `// This code is contributed by phasing17`

## Javascript

 ``

Output

`5`

Complexity Analysis:

Time Complexity: O(n).
Space Complexity: O(n), for the Hash Map

My Personal Notes arrow_drop_up
Recommended Articles
Page :