Count of subarray that does not contain any subarray with sum 0 - GeeksforGeeks

15 Feb, 2022
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 are 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  
 
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.
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 above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero #include <bits/stdc++.h>using namespace std; // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0void numberOfSubarrays(int arr[], int n){    vector<int> v(n + 1);    v[0] = 0;     // Storing each element as sum    // of its previous element    for (int i = 0; i < n; i++) {        v[i + 1] = v[i] + arr[i];    }     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;        }         // Check if another same element found        // this means a subarray exist between        // end and begin whose sum        // of elements is equal to 0        answer = answer + end - begin;         // Erase beginning element from map        mp.erase(v[begin]);         // Increase begin        begin++;    }     // Print the result    cout << answer << endl;} // Driver Codeint main(){     int arr[] = { 2, 4, -6 };    int size = sizeof(arr) / sizeof(arr[0]);     numberOfSubarrays(arr, size);     return 0;}
// Java program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zeroimport java.util.*; class GFG{  // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int arr[], int n){    int []v = new int[n + 1];    v[0] = 0;      // Storing each element as sum    // of its previous element    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);        }          // Check if another same element found        // this means a subarray exist between        // end and begin whose sum        // of elements is equal to 0        answer = answer + end - begin;          // Erase beginning element from map        mp.remove(v[begin]);          // Increase begin        begin++;    }      // Print the result    System.out.print(answer +"\n");}  // Driver Codepublic static void main(String[] args){      int arr[] = { 2, 4, -6 };    int size = arr.length;      numberOfSubarrays(arr, size);}} // This code is contributed by sapnasingh4991
# Python 3 program to Count the no of subarray# which do not contain any subarray# whose sum of elements is equal to zero # Function that print the number of# subarrays which do not contain any subarray# whose elements sum is equal to 0def numberOfSubarrays(arr, n):     v = [0]*(n + 1)     # Storing each element as sum    # of its previous element    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         # Check if another same element found        # this means a subarray exist between        # end and begin whose sum        # of elements is equal to 0        answer = answer + end - begin         # Erase beginning element from map        del mp[v[begin]]         # Increase begin        begin += 1     # Print the result    print(answer) # Driver Codeif __name__ == "__main__":         arr = [ 2, 4, -6 ]    size = len(arr)    numberOfSubarrays(arr, size) # This code is contributed by chitranayal
// C# program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zerousing System;using System.Collections.Generic; class GFG{   // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0static void numberOfSubarrays(int []arr, int n){    int []v = new int[n + 1];    v[0] = 0;       // Storing each element as sum    // of its previous element    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);        }           // Check if another same element found        // this means a subarray exist between        // end and begin whose sum        // of elements is equal to 0        answer = answer + end - begin;           // Erase beginning element from map        mp.Remove(v[begin]);           // Increase begin        begin++;    }       // Print the result    Console.Write(answer +"\n");}   // Driver Codepublic static void Main(String[] args){       int []arr = { 2, 4, -6 };    int size = arr.Length;       numberOfSubarrays(arr, size);}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to Count the no of subarray// which do not contain any subarray// whose sum of elements is equal to zero // Function that print the number of// subarrays which do not contain any subarray// whose elements sum is equal to 0function numberOfSubarrays(arr, n){    let v = new Array(n + 1);    v[0] = 0;     // Storing each element as sum    // of its previous element    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);        }         // Check if another same element found        // this means a subarray exist between        // end and begin whose sum        // of elements is equal to 0        answer = answer + end - begin;         // Erase beginning element from map        mp.clear();         // Increase begin        begin++;    }     // Print the result    document.write(answer + "<br>");} // Driver Code let arr = [ 2, 4, -6 ];let size = arr.length; numberOfSubarrays(arr, size); // This code is contributed by _saurabh_jaiswal </script>
5
 
Time Complexity: O(N)
Auxiliary Space: O(N)
ukasp
sapnasingh4991
Rajput-Ji
Akanksha_Rai
_saurabh_jaiswal
bharani19797
rohitsingh07052
subarray
subarray-sum
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Linked List vs Array
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Given an array of size n and a number k, find all elements that appear more than n/k times