Open In App

Find the length of largest subarray with 0 sum

Last Updated : 03 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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}

Recommended Practice

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 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 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 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




<?php
// PHP program for the above approach
 
// Returns length of the
// largest subarray with 0 sum
function 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 call
echo "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>


Output

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 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 (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<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 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




<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>


Output

Length of the longest 0 sum subarray is 5

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



Previous Article
Next Article

Similar Reads

Maximize product of min value of subarray and sum of subarray over all subarrays of length K
Given an array arr[] of N integers, the task is to find the maximum possible value of (min * sum) among all possible subarrays having K elements, where min denotes the smallest integer of the subarray and sum denotes the sum of all elements of the subarray. Example: Input: arr[] = {1, 2, 3, 2}, K = 3Output: 14Explanation: For the subarray {2, 3, 2}
7 min read
Maximum length of subarray such that sum of the subarray is even
Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even.Examples: Input : N = 6, arr[] = {1, 2, 3, 2, 1, 4}Output : 5Explanation: In the example the subarray in range [2, 6] has sum 12 which is even, so the length is 5.Input : N = 4, arr[] = {1, 2, 3, 2}Output : 4Recommended: Please
11 min read
Find the length of largest subarray in which all elements are Autobiographical Numbers
Given an array arr[] of integers, our task is to find the length of the largest subarray such that all the elements of the sub-array are Autobiographical Number. An Autobiographical Number is a number such that the first digit of it counts how many zeroes are there in it, the second digit counts how many ones are there and so on. For example, 21200
8 min read
First subarray having sum at least half the maximum sum of any subarray of size K
Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum possible sum from any subarray of size K is 16 fr
9 min read
Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2, 3, 4} Output: 1 Explanation: All identical elemen
5 min read
Find minimum subarray sum for each index i in subarray [i, N-1]
Given an array arr[] of size N, the task is to find the minimum subarray sum in the subarrays [i, N-1] for all i in [0, N-1]. Examples: Input: arr[ ] = {3, -1, -2}Output: -3 -3 -2Explanation: For (i = 1) i.e. {3, -1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 2) i.e. {-1, -2}, the minimum subarray sum is -3 for {-1, -2}.For (i = 3) i
9 min read
Length of the largest subarray with contiguous elements | Set 1
Given an array of distinct integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. Examples: Input: arr[] = {10, 12, 11}; Output: Length of the longest contiguous subarray is 3 Input: arr[] = {14, 12, 11, 20}; Output: Length of the longest contiguous subarray is 2 Input: arr[] = {1, 56, 58
7 min read
Length of the largest subarray with contiguous elements | Set 2
Given an array of integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence. In the previous post, we have discussed a solution that assumes that elements in given array are distinct. Here we discuss a solution that works even if the input array has duplicates. Examples: Input: arr[] = {10, 1
7 min read
Length of longest subarray for each index in Array where element at that index is largest
Given an array arr[] of size N, the task is to calculate, for i(0&lt;=i&lt;N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which 1st index element is maximum is 1, the subarray c
15 min read
Length of largest subarray whose all elements are Perfect Number
Given an array arr[] of integer elements, the task is to find the length of the largest sub-array of arr[] such that all the elements of the sub-array are Perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors. Examples: Input: arr[] = {1, 7, 36, 4, 6, 28, 4} Output: 2 Explanation: Maximum length sub-
7 min read