×

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

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

ATM machine program in C++ using functions

Automated Teller Machines (ATMs) carry out daily financial transactions. They are straightforward and simple, allowing customers to complete self-service transactions quickly. ATMs can then be used to withdraw cash, deposit...

3 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

C++ cin and cout

In this article, we will discuss the C++ cin and cout with their library and examples. C++ Standard Input/Output: User-program communication is made possible by C++’s usage of input and output (I/O)...

5 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

Single level Inheritance

Inheritance is a fundamental element of C++’s Object-Oriented Programming (OOP). It allows a class (called the derived class) to inherit characteristics and attributes from another class (called the base class)....

5 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

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