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 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 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 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 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 curr_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)
Find the length of the largest subarray with 0 sum using hashmap:
Follow the below idea to solve the problem using this approach:Â
Let us say prefixsum of array till index i is represented as Si .
Now consider two indices i and j (j > i) such that Si = Sj .So,Â
Si = arr[0] + arr[1] + . . . + arr[i]
Sj = arr[0] + arr[1] + . . . + arr[i] + arr[i+1] + . . . + arr[j]Now if we subtract Si from Sj .
Sj – Si = (arr[0] + arr[1] + . . . + arr[i] + arr[i+1] + . . . + arr[j]) – (arr[0] + arr[1] + . . . + arr[i])
0 = (arr[0] – arr[0]) + (arr[1] – arr[1]) + . . . + (arr[i] – arr[i]) + arr[i+1] + arr[i+2] + . . . + arr[j]
0 = arr[i+1] + arr[i+2] + . . . + arr[j]So we can see if there are two indices i and j (j > i) for which the prefix sum are same then the subarray from i+1 to j has sum = 0.
We can use hashmap to store the prefix sum, and if we reach any index for which there is already a prefix with same sum, we will find a subarray with sum as 0. Compare the length of that subarray with the current longest subarray and update the maximum value accordingly.
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 (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 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<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 (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 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 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
<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)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

