# Find the length of largest subarray with 0 sum

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

Given an array arr[] of length N, find the length of the longest sub-array with a sum equal 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: Follow the steps below to solve the problem using this approach:

• Consider all sub-arrays one by one and check the sum of every sub-array.
• If the sum of the current subarray is equal to zero then update the maximum length accordingly

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#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's Code``int` `main()``{``    ``int` `arr[] = {15, -2, 2, -8, 1, 7, 10, 23};``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);``  ` `  ``// Function call``    ``cout << ``"Length of the longest 0 sum subarray is "``         ``<< maxLen(arr, N);``    ``return` `0;``}`

## Java

 `// Java code for the above approach` `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's code``    ``public` `static` `void` `main(String args[])``    ``{``        ``int` `arr[] = {``15``, -``2``, ``2``, -``8``, ``1``, ``7``, ``10``, ``23``};``        ``int` `N = arr.length;``      ` `      ``// Function call``        ``System.out.println(``"Length of the longest 0 sum "``                           ``+ ``"subarray is "` `+ maxLen(arr, N));``    ``}``}`

## Python3

 `# Python program for the above approach` `# 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` `# Driver's code``if` `__name__ ``=``=` `"__main__"``:``# test array``    ``arr ``=` `[``15``, ``-``2``, ``2``, ``-``8``, ``1``, ``7``, ``10``, ``13``]``    ` `    ``# Function call``    ``print` `(``"Length of the longest 0 sum subarray is % d"` `%` `maxLen(arr))`

## C#

 `// C# code for the above approach``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's code``    ``static` `public` `void` `Main()``    ``{``        ``int``[] arr = {15, -2, 2, -8,``                      ``1, 7, 10, 23};``        ``int` `N = arr.Length;``        ` `        ``// Function call``        ``Console.WriteLine(``"Length of the longest 0 sum "``                          ``+ ``"subarray is "` `+ maxLen(arr, N));``    ``}``}`

## PHP

 ``

## Javascript

 ``

Output

`Length of the longest 0 sum subarray is 5`

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach 1 (Hash map):  Follow the below idea to solve the problem using this approach:

Create a variable sum and while traversing the input array, for every index add the value of the element into the sum variable and then store the sum-index pair in a hash-map. 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

Follow the steps mentioned below to implement the approach:

• Create a variable (sum), length (max_len), and a hash map (hm) to store the sum-index pair as a key-value pair.
• Traverse the input array and For every index, update the value of sum = sum + array[i].
• Check every index, if the current sum is present in the hash map or not.
• 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.
• 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:

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#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's Code``int` `main()``{``    ``int` `arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``// Function call``    ``cout << ``"Length of the longest 0 sum subarray is "``         ``<< maxLen(arr, N);` `    ``return` `0;``}`

## Java

 `// Java program for the above approach` `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's code``    ``public` `static` `void` `main(String arg[])``    ``{``        ``int` `arr[] = {``15``, -``2``, ``2``, -``8``, ``1``, ``7``, ``10``, ``23``};` `        ``// Function call``        ``System.out.println(``            ``"Length of the longest 0 sum subarray is "``            ``+ maxLen(arr));``    ``}``}`

## Python3

 `# Python program for the above approach` `# Returns the maximum length`  `def` `maxLen(arr):` `    ``# NOTE: Dictionary in python is``    ``# 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] ``=``=` `0` `and` `max_len ``=``=` `0``:``            ``max_len ``=` `1` `        ``if` `curr_sum ``=``=` `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`  `# Driver's code``if` `__name__ ``=``=` `"__main__"``:` `    ``# test array``    ``arr ``=` `[``15``, ``-``2``, ``2``, ``-``8``, ``1``, ``7``, ``10``, ``13``]` `    ``# Function call``    ``print``(``"Length of the longest 0 sum subarray is % d"` `%` `maxLen(arr))`

## C#

 `// C# program for the above approach` `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's code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] arr = { 15, -2, 2, -8, 1, 7, 10, 23 };` `        ``// Function call``        ``Console.WriteLine(``            ``"Length of the longest 0 sum subarray is "``            ``+ maxLen(arr));``    ``}``}`

## Javascript

 ``

Output

`Length of the longest 0 sum subarray is 5`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up