Count of subarray that does not contain any subarray with sum 0
Last Updated :
14 Oct, 2023
Given an array arr, the task is to find the total number of subarrays of the given array which do not contain any subarray whose sum of elements is equal to zero. All the array elements may not be distinct.
Examples:
Input: arr = {2, 4, -6}
Output: 5
Explanation:
There are 5 subarrays which do not contain any subarray whose elements sum is equal to zero: [2], [4], [-6], [2, 4], [4, -6]
Input: arr = {10, -10, 10}
Output: 3
Naive Approach-
The idea is to find all subarrays and then find those subarrays whose any of the subarrays does not have a sum equal to zero.
Steps to implement-
- Declare a variable count with value 0 to store the final answer
- Run two for loops to find all subarray
- For each subarray find its all subarray by running two another for loops
- If it’s every subarray has a non-zero sum then increment the count
- In the last print the value of the count
Code-
C++
#include <bits/stdc++.h>
using namespace std;
void numberOfSubarrays( int arr[], int N)
{
int count=0;
for ( int i=0;i<N;i++){
for ( int j=i;j<N;j++){
bool val= true ;
for ( int m=i;m<=j;m++){
int sum=0;
for ( int n=m;n<=j;n++){
sum+=arr[n];
if (sum==0){
val= false ;
break ;
}
}
if (val== false ){ break ;}
}
if (val== true ){count++;}
}
}
cout<<count<<endl;
}
int main()
{
int arr[] = { 2, 4, -6 };
int size = sizeof (arr) / sizeof (arr[0]);
numberOfSubarrays(arr, size);
return 0;
}
|
Java
public class SubarraySum {
public static int numberOfSubarrays( int [] arr, int N) {
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i; j < N; j++) {
boolean val = true ;
for ( int m = i; m <= j; m++) {
int sum = 0 ;
for ( int n = m; n <= j; n++) {
sum += arr[n];
if (sum == 0 ) {
val = false ;
break ;
}
}
if (!val) {
break ;
}
}
if (val) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int [] arr = { 2 , 4 , - 6 };
int size = arr.length;
int result = numberOfSubarrays(arr, size);
System.out.println(result);
}
}
|
Python
def numberOfSubarrays(arr):
N = len (arr)
count = 0
for i in range (N):
for j in range (i, N):
val = True
for m in range (i, j + 1 ):
s = 0
for n in range (m, j + 1 ):
s + = arr[n]
if s = = 0 :
val = False
break
if not val:
break
if val:
count + = 1
return count
arr = [ 2 , 4 , - 6 ]
print (numberOfSubarrays(arr))
|
C#
using System;
public class GFG {
public static void NumberOfSubarrays( int [] arr, int N) {
int count=0;
for ( int i=0; i<N; i++){
for ( int j=i; j<N; j++){
bool val= true ;
for ( int m=i; m<=j; m++){
int sum=0;
for ( int n=m; n<=j; n++){
sum += arr[n];
if (sum==0){
val = false ;
break ;
}
}
if (val== false ) { break ; }
}
if (val== true ) { count++; }
}
}
Console.WriteLine(count);
}
public static void Main( string [] args) {
int [] arr = { 2, 4, -6 };
int size = arr.Length;
NumberOfSubarrays(arr, size);
}
}
|
Javascript
function numberOfSubarrays(arr) {
let count = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
let val = true ;
for (let m = i; m <= j; m++) {
let sum = 0;
for (let n = m; n <= j; n++) {
sum += arr[n];
if (sum === 0) {
val = false ;
break ;
}
}
if (val === false ) {
break ;
}
}
if (val === true ) {
count++;
}
}
}
console.log(count);
}
const arr = [2, 4, -6];
numberOfSubarrays(arr);
|
Output-
5
Time Complexity: O(N4), because two loops to find all subarray and two more loops to find all subarray of a particular subarray
Auxiliary Space: O(1), because no extra space has been used
Approach:
- Firstly store all elements of array as sum of its previous element.
- Now take two pointers, increase second pointer and store the value in a map while a same element not encounter.
- If an element encounter which is already exist in map, this means there exist a subarray between two pointers whose elements sum is equal to 0.
- Now increase first pointer and remove the element from map while the two same elements exists.
- Store the answer in a variable and finally return it.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void numberOfSubarrays( int arr[], int n)
{
vector< int > v(n + 1);
v[0] = 0;
for ( int i = 0; i < n; i++) {
v[i + 1] = v[i] + arr[i];
}
unordered_map< int , int > mp;
int begin = 0, end = 0, answer = 0;
mp[0] = 1;
while (begin < n) {
while (end < n
&& mp.find(v[end + 1])
== mp.end()) {
end++;
mp[v[end]] = 1;
}
answer = answer + end - begin;
mp.erase(v[begin]);
begin++;
}
cout << answer << endl;
}
int main()
{
int arr[] = { 2, 4, -6 };
int size = sizeof (arr) / sizeof (arr[0]);
numberOfSubarrays(arr, size);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void numberOfSubarrays( int arr[], int n)
{
int []v = new int [n + 1 ];
v[ 0 ] = 0 ;
for ( int i = 0 ; i < n; i++) {
v[i + 1 ] = v[i] + arr[i];
}
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
int begin = 0 , end = 0 , answer = 0 ;
mp.put( 0 , 1 );
while (begin < n) {
while (end < n
&& !mp.containsKey(v[end + 1 ])) {
end++;
mp.put(v[end], 1 );
}
answer = answer + end - begin;
mp.remove(v[begin]);
begin++;
}
System.out.print(answer + "\n" );
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , - 6 };
int size = arr.length;
numberOfSubarrays(arr, size);
}
}
|
Python3
def numberOfSubarrays(arr, n):
v = [ 0 ] * (n + 1 )
for i in range ( n):
v[i + 1 ] = v[i] + arr[i]
mp = {}
begin, end, answer = 0 , 0 , 0
mp[ 0 ] = 1
while (begin < n):
while (end < n
and (v[end + 1 ]) not in mp):
end + = 1
mp[v[end]] = 1
answer = answer + end - begin
del mp[v[begin]]
begin + = 1
print (answer)
if __name__ = = "__main__" :
arr = [ 2 , 4 , - 6 ]
size = len (arr)
numberOfSubarrays(arr, size)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void numberOfSubarrays( int []arr, int n)
{
int []v = new int [n + 1];
v[0] = 0;
for ( int i = 0; i < n; i++) {
v[i + 1] = v[i] + arr[i];
}
Dictionary< int , int > mp = new Dictionary< int , int >();
int begin = 0, end = 0, answer = 0;
mp.Add(0, 1);
while (begin < n) {
while (end < n
&& !mp.ContainsKey(v[end + 1])) {
end++;
mp.Add(v[end], 1);
}
answer = answer + end - begin;
mp.Remove(v[begin]);
begin++;
}
Console.Write(answer + "\n" );
}
public static void Main(String[] args)
{
int []arr = { 2, 4, -6 };
int size = arr.Length;
numberOfSubarrays(arr, size);
}
}
|
Javascript
<script>
function numberOfSubarrays(arr, n)
{
let v = new Array(n + 1);
v[0] = 0;
for (let i = 0; i < n; i++) {
v[i + 1] = v[i] + arr[i];
}
let mp = new Map();
let begin = 0, end = 0, answer = 0;
mp.set(0, 1);
while (begin < n) {
while (end < n && !mp.has(v[end + 1])) {
end++;
mp.set(v[end], 1);
}
answer = answer + end - begin;
mp.clear();
begin++;
}
document.write(answer + "<br>" );
}
let arr = [ 2, 4, -6 ];
let size = arr.length;
numberOfSubarrays(arr, size);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...