C++ Program to find largest subarray with 0 sum
Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns out to be zero.
Example
Input:
arr[] = {18, -2, 2, -8, 1, 7, 10, 25};
Output:
5
Explanation: The elements forming the longest subarray are {-2, 2, -8, 1, 7}
Input:
arr[] = {1, 2, 3, 4, 5}
Output:
0
Explanation: All the numbers are in increasing order so no subarray with 0 sum
Input:
arr[] = {1, 0, 3, 5, 7, 10}
Output:
1
Explanation: There is a single element in the array that is 0. So it is the only largest subarray formed.
Naive approach (Brute force)
The brute force approach uses two loops.
The outer loop fixes the starting of the subarray and the inner loop runs until the sum of the array elements becomes 0. Whenever the sum becomes 0 the count is maintained and the largest subarray is calculated.
C++ code
#include <bits/stdc++.h>
using namespace std;
int maxLensubarray(int arr[], int n) // function to find the largest subarray
{
int max_len = 0; // let the resultant length is 0
for (int i = 0; i < n; i++) { // run the outer loop
int curr_sum = 0; // For a particular window the current sum is 0
for (int j = i; j < n; j++) { // inner loop find the sum 0
curr_sum += arr[j];
if (curr_sum == 0) // if the subarray is found with sum 0
max_len = max(max_len, j - i + 1); // update the result
}
}
return max_len; // return result
}
int main()
{
int arr[] = {18, -2, 2, -8, 1, 7, 10, 25};
int n = sizeof(arr) / sizeof(arr[0]); // find size of array
cout << " The Length of the longest 0 sum subarray is "
<< maxLensubarray(arr, n);
return 0;
}
Output
The Length of the longest 0 sum subarray is 5
C code
#include<stdio.h>
#include<stdlib.h>
int maxLensubarray(int arr[], int n) // function to find the largest subarray
{
int max_len = 0; // let the resultant length is 0
for (int i = 0; i < n; i++) { // run the outer loop
int curr_sum = 0; // For a particular window the current sum is 0
for (int j = i; j < n; j++) { // inner loop find the sum 0
curr_sum += arr[j];
if (curr_sum == 0) // if the subarray is found with sum 0
if (max_len <(j-i+1))
max_len= j - i + 1; // update the result
}
}
return max_len; // return result
}
int main()
{
int arr[] = {18, -2, 2, -8, 1, 7, 10, 25};
int n = sizeof(arr) / sizeof(arr[0]); // find size of array
printf( " The Length of the longest 0 sum subarray is %d", maxLensubarray(arr, n));
return 0;
}
Output
The Length of the longest 0 sum subarray is 5
Time complexity - O(n*n)
Space complexity - O(1)
Optimised approach
The problem with the brute force approach is that it calculates the subarray sum again and again.
This problem can be solved by taking an extra space hashmap. The new array formed will store the sum of all the elements upto that particular index. We will store the pair of sum-indexes in a hashmap as it allows insertion, deletion in constant time.
Hence, if the sum appears twice in the array it is guaranteed that there is a subarray with 0 sum and the difference between the indices will be returned.
- Create an array prefix of length n, a variable sum, length of subarray max_len, and a hashmap to store sum-index pair.
- Run a loop from start to end
- For every index update the sum as
Sum+=arr[i]
- Now check if the current sum is present in the hashmap or not
- If present update max_len as difference between the i and the index in the hashmap
- If sum is not present in the hashmap, insert the sum-index pair into the hashmap
- Print the max_len
C++ code
#include <bits/stdc++.h>
using namespace std;
int maxLensubarray(int arr[], int n) // function to find the max subarray length with sum 0
{
unordered_map<int, int> presum; // map to store the sum-index pair
int sum = 0; // current sum is 0
int max_len = 0; // max len result is 0
for (int i = 0; i < n; i++) { // Iterate in the array
sum += arr[i]; // Find the current sum
if (arr[i] == 0 && max_len == 0) // base case
max_len = 1;
if (sum == 0)
max_len = i + 1; // increment the result count length
// Search if the sum is present in the hashtable
if (presum.find(sum) != presum.end()) {
// If this sum is seen before, then update max_len
max_len = max(max_len, i - presum[sum]); // new max_len
}
else {
// Else insert this sum with index in hash table
presum[sum] = i; // insert into hashmap
}
}
return max_len;
}
int main()
{
int arr[] = {18, -2, 2, -8, 1, 7, 10, 25}; // initialise the array
int n = sizeof(arr) / sizeof(arr[0]); // find size of array
cout << " The Length of the longest 0 sum subarray is " << maxLensubarray(arr, n); // Call the function to print the answer
return 0;
}
Output
The Length of the longest 0 sum subarray is 5
Time complexity - O(n)
Space complexity - O(n)