Find the length of largest subarray with 0 sum
Last Updated :
03 Mar, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int maxLen( int arr[], int N)
{
int max_len = 0;
for ( int i = 0; i < N; i++) {
int curr_sum = 0;
for ( int j = i; j < N; j++) {
curr_sum += arr[j];
if (curr_sum == 0)
max_len = max(max_len, j - i + 1);
}
}
return max_len;
}
int main()
{
int arr[] = {15, -2, 2, -8, 1, 7, 10, 23};
int N = sizeof (arr) / sizeof (arr[0]);
cout << "Length of the longest 0 sum subarray is "
<< maxLen(arr, N);
return 0;
}
|
Java
class GFG {
static int maxLen( int arr[], int N)
{
int max_len = 0 ;
for ( int i = 0 ; i < N; i++) {
int curr_sum = 0 ;
for ( int j = i; j < N; j++) {
curr_sum += arr[j];
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));
}
}
|
Python3
def maxLen(arr):
max_len = 0
for i in range ( len (arr)):
curr_sum = 0
for j in range (i, len (arr)):
curr_sum + = arr[j]
if curr_sum = = 0 :
max_len = max (max_len, j - i + 1 )
return max_len
if __name__ = = "__main__" :
arr = [ 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 13 ]
print ( "Length of the longest 0 sum subarray is % d" % maxLen(arr))
|
C#
using System;
class GFG {
static int maxLen( int [] arr, int N)
{
int max_len = 0;
for ( int i = 0; i < N; i++) {
int curr_sum = 0;
for ( int j = i; j < N; j++) {
curr_sum += arr[j];
if (curr_sum == 0)
max_len = Math.Max(max_len,
j - i + 1);
}
}
return max_len;
}
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));
}
}
|
PHP
<?php
function maxLen( $arr , $N )
{
$max_len = 0;
for ( $i = 0; $i < $N ; $i ++)
{
$curr_sum = 0;
for ( $j = $i ; $j < $N ; $j ++)
{
$curr_sum += $arr [ $j ];
if ( $curr_sum == 0)
$max_len = max( $max_len ,
$j - $i + 1);
}
}
return $max_len ;
}
$arr = array (15, -2, 2, -8,
1, 7, 10, 23);
$N = sizeof( $arr );
echo "Length of the longest 0 " .
"sum subarray is " ,
maxLen( $arr , $N );
?>
|
Javascript
<script>
function maxLen(arr, N)
{
let max_len = 0;
for (let i = 0; i < N; i++) {
let curr_sum = 0;
for (let j = i; j < N; j++) {
curr_sum += arr[j];
if (curr_sum == 0)
max_len = Math.max(max_len, j - i + 1);
}
}
return max_len;
}
let arr = [15, -2, 2, -8, 1, 7, 10, 23];
let N = arr.length;
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++
#include <bits/stdc++.h>
using namespace std;
int maxLen( int arr[], int N)
{
unordered_map< int , int > presum;
int sum = 0;
int max_len = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
if (sum == 0)
max_len = i + 1;
if (presum.find(sum) != presum.end()) {
max_len = max(max_len, i - presum[sum]);
}
else {
presum[sum] = i;
}
}
return max_len;
}
int main()
{
int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << "Length of the longest 0 sum subarray is "
<< maxLen(arr, N);
return 0;
}
|
Java
import java.util.HashMap;
class MaxLenZeroSumSub {
static int maxLen( int arr[])
{
HashMap<Integer, Integer> hM
= new HashMap<Integer, Integer>();
int sum = 0 ;
int max_len = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
sum += arr[i];
if (sum == 0 )
max_len = i + 1 ;
Integer prev_i = hM.get(sum);
if (prev_i != null )
max_len = Math.max(max_len, i - prev_i);
else
hM.put(sum, i);
}
return max_len;
}
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
def maxLen(arr):
hash_map = {}
max_len = 0
curr_sum = 0
for i in range ( len (arr)):
curr_sum + = arr[i]
if curr_sum = = 0 :
max_len = i + 1
if curr_sum in hash_map:
max_len = max (max_len, i - hash_map[curr_sum])
else :
hash_map[curr_sum] = i
return max_len
if __name__ = = "__main__" :
arr = [ 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 13 ]
print ( "Length of the longest 0 sum subarray is % d" % maxLen(arr))
|
C#
using System;
using System.Collections.Generic;
public class MaxLenZeroSumSub {
static int maxLen( int [] arr)
{
Dictionary< int , int > hM
= new Dictionary< int , int >();
int sum = 0;
int max_len = 0;
for ( int i = 0; i < arr.GetLength(0); i++) {
sum += arr[i];
if (arr[i] == 0 && max_len == 0)
max_len = 1;
if (sum == 0)
max_len = i + 1;
int prev_i = 0;
if (hM.ContainsKey(sum)) {
prev_i = hM[sum];
}
if (hM.ContainsKey(sum))
max_len = Math.Max(max_len, i - prev_i);
else {
if (hM.ContainsKey(sum))
hM.Remove(sum);
hM.Add(sum, i);
}
}
return max_len;
}
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));
}
}
|
Javascript
<script>
function maxLen(arr)
{
let hM = new Map();
let sum = 0;
let max_len = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
if (arr[i] == 0 && max_len == 0)
max_len = 1;
if (sum == 0)
max_len = i + 1;
let prev_i = hM.get(sum);
if (prev_i != null )
max_len = Math.max(max_len, i - prev_i);
else
hM.set(sum, i);
}
return max_len;
}
let arr = [15, -2, 2, -8, 1, 7, 10, 23];
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)
Please Login to comment...