×

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)


Related Topics

C++ Call by Reference

Call by Reference is a C++ method for passing arguments to a function that enables us to pass the actual memory address of the parameter rather than a copy of...

4 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

wcscpy(), wcslen(), wcscmp() Functions in C++

There are many built-in functions in C++ programming language which differentiate it from C programming language in most hardware-coded languages. We will now closely look into the applications of three...

4 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

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

4 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

How to calculate size of string in C++

What is string in C++? In C++, a string is a sequence of characters. The string data type is part of the Standard Template Library (STL) and is defined in the...

4 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.