Find the length of largest subarray with 0 sum
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 sumInput: 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 <bits/stdc++.h>using namespace std;// Returns length of the largest// subarray with 0 sumint 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 Codeint 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 approachclass 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 lengthdef 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 codeif __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 approachusing 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
<?php// PHP program for the above approach// Returns length of the// largest subarray with 0 sumfunction maxLen($arr, $N){ // Initialize result $max_len = 0; // Pick a starting point for ($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 required if ($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);// Function callecho "Length of the longest 0 " . "sum subarray is ", maxLen($arr, $N); ?> |
Javascript
<script> // Javascript code to find the largest // subarray with 0 sum // Returns length of the // largest subarray with 0 sum function maxLen(arr, N) { let max_len = 0; // Pick a starting point for (let i = 0; i < N; i++) { // Initialize curr_sum // for every starting point let curr_sum = 0; // try all subarrays // starting with 'i' for (let 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 let arr = [15, -2, 2, -8, 1, 7, 10, 23]; let N = arr.length; // Function call document.write("Length of the longest 0 sum " + "subarray is " + maxLen(arr, N)); </script> |
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 <bits/stdc++.h>using namespace std;// Returns Length of the required subarrayint 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 Codeint 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 approachimport 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<Integer, Integer> hM = new HashMap<Integer, Integer>(); 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 lengthdef 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 codeif __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 approachusing 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
<script>// Javascript program to find maximum length subarray with 0 sum // Returns length of the maximum length subarray with 0 sum function maxLen(arr) { // Creates an empty hashMap hM let hM = new Map(); let sum = 0; // Initialize sum of elements let max_len = 0; // Initialize result // Traverse through the given array for (let 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 let 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.set(sum, i); } return max_len; }// Driver's program let arr = [15, -2, 2, -8, 1, 7, 10, 23]; // Function call document.write("Length of the longest 0 sum subarray is " + maxLen(arr)); </script> |
Length of the longest 0 sum subarray is 5
Time Complexity: O(N)
Auxiliary Space: O(N)



.png)