Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count subarrays having sum modulo K same as the length of the subarray
Next article icon

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

Last Updated : 14 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// 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 0 void numberOfSubarrays(int arr[], int N) {     //To store final answer     int count=0;         //Find all subarray    for(int i=0;i<N;i++){       for(int j=i;j<N;j++){                      //Boolean variable to tell whether its any subarray           //have sum is equal to zero or not           bool val=true;                      //Find all subarray of this subarray           for(int m=i;m<=j;m++){               //To store sum of all elements of subarray               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++;}      }     }    //Print final answer    cout<<count<<endl; }  // Driver Code int main() {     int arr[] = { 2, 4, -6 };     int size = sizeof(arr) / sizeof(arr[0]);     numberOfSubarrays(arr, size);     return 0; } 
Java
public class SubarraySum {      // Function that returns the number of subarrays which do not contain     // any subarray whose elements sum is equal to 0     public static int numberOfSubarrays(int[] arr, int N) {         // To store the final answer         int count = 0;          // Find all subarrays         for (int i = 0; i < N; i++) {             for (int j = i; j < N; j++) {                  // Boolean variable to tell whether any subarray has sum equal to zero or not                 boolean val = true;                  // Find all subarrays of this subarray                 for (int m = i; m <= j; m++) {                     // To store sum of all elements of subarray                     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);          // This Code Is Contributed By Shubham Tiwari     } } 
Python
# Function that returns the number of # subarrays which do not contain any subarray # whose elements sum is equal to 0 def numberOfSubarrays(arr):     N = len(arr)     # To store the final answer     count = 0          # Find all subarrays     for i in range(N):         for j in range(i, N):                          # Boolean variable to tell whether any subarray             # has a sum equal to zero or not             val = True                          # Find all subarrays of this subarray             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 the final answer     return count  # Driver Code arr = [2, 4, -6] print(numberOfSubarrays(arr)) #This Code Is Contributed By Shubham Tiwari 
C#
using System;  public class GFG {     // Function that print the number of     // subarrays which do not contain any subarray     // whose elements sum is equal to 0     public static void NumberOfSubarrays(int[] arr, int N) {         //To store final answer         int count=0;                 //Find all subarray        for(int i=0; i<N; i++){           for(int j=i; j<N; j++){                              //Boolean variable to tell whether its any subarray               //have sum is equal to zero or not               bool val=true;                              //Find all subarray of this subarray               for(int m=i; m<=j; m++){                   //To store sum of all elements of subarray                   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++; }          }         }        //Print final answer        Console.WriteLine(count);     }      // Driver Code     public static void Main(string[] args) {         int[] arr = { 2, 4, -6 };         int size = arr.Length;         NumberOfSubarrays(arr, size);                  // This Code Is Contributed By Shubham Tiwari     } } 
JavaScript
// Function that prints the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 function numberOfSubarrays(arr) {     // To store final answer     let count = 0;      // Find all subarrays     for (let i = 0; i < arr.length; i++) {         for (let j = i; j < arr.length; j++) {              // Boolean variable to tell whether any subarray             // has a sum equal to zero or not             let val = true;              // Find all subarrays of this subarray             for (let m = i; m <= j; m++) {                 // To store the sum of all elements of subarray                 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++;             }         }     }     // Print the final answer     console.log(count); }  // Driver Code const arr = [2, 4, -6]; numberOfSubarrays(arr);  // This code is contributed by rambabuguphka 

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: 

  1. Firstly store all elements of array as sum of its previous element. 
     
  2. Now take two pointers, increase second pointer and store the value in a map while a same element not encounter. 
     
  3. 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. 
     
  4. Now increase first pointer and remove the element from map while the two same elements exists. 
     
  5. Store the answer in a variable and finally return it.


Below is the implementation of the above approach: 

C++
// 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 0 void 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];     }      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;         }          // 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 Code int main() {      int arr[] = { 2, 4, -6 };     int size = sizeof(arr) / sizeof(arr[0]);      numberOfSubarrays(arr, size);      return 0; } 
Java
// Java program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero import java.util.*;  class GFG{   // Function that print the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 static 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 Code public static void main(String[] args) {       int arr[] = { 2, 4, -6 };     int size = arr.length;       numberOfSubarrays(arr, size); } }  // This code is contributed by sapnasingh4991 
Python3
# 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 0 def 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 Code if __name__ == "__main__":          arr = [ 2, 4, -6 ]     size = len(arr)     numberOfSubarrays(arr, size)  # This code is contributed by chitranayal  
C#
// C# program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero using 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 0 static 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 Code public static void Main(String[] args) {        int []arr = { 2, 4, -6 };     int size = arr.Length;        numberOfSubarrays(arr, size); } }  // This code is contributed by Rajput-Ji 
JavaScript
<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 0 function 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> 

Output
5

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Count subarrays having sum modulo K same as the length of the subarray

N

nitinkr8991
Improve
Article Tags :
  • Misc
  • DSA
  • Arrays
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Misc

Similar Reads

  • Count of Subarrays which Contain the Length of that Subarray
    Given an array A[] of length N, the task is to count the number of subarrays of A[] that contain the length of that subarray. Examples: Input: A = {10, 11, 1}, N = 3Output: 1Explanation: Only the subarray {1}, with a length 1, contains its own length. Input: A = [1, 2, 3, 4, 5], N = 5Output: 9Explan
    8 min read
  • Count Subarrays with product of sum and subarray length less than K
    Given an array of positive elements arr[] of length N, the task is to count all the subarrays such that the product of the subarray sum and length of the subarray should be strictly less than K. Examples: Input: arr[] = {6, 2, 1, 4, 3}, K = 10Output: 6Explanation: There are six valid subarrays: {6},
    13 min read
  • Count of Subarrays in an array containing numbers from 1 to the length of subarray
    Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array. Examples: Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1
    7 min read
  • Count subarrays having sum modulo K same as the length of the subarray
    Given an integer K and an array arr[] consisting of N positive integers, the task is to find the number of subarrays whose sum modulo K is equal to the size of the subarray. Examples: Input: arr[] = {1, 4, 3, 2}, K = 3Output: 4Explanation: 1 % 3 = 1 (1 + 4) % 3 = 2 4 % 3 = 1 (3 + 2) % 3 = 2 Therefor
    15 min read
  • Count of subarrays with unique sum with sum at most K
    Given an array arr[] of size N and an integer K., The task is to count the number of subarrays with unique sum with sum at most K. Examples: Input: N = 3, arr[] = {1, 0, 1}, K = 1Output: 2Explanation: All Subarrays are [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] & The sum of these subarrays are {1,
    4 min read
  • Count of subarrays with sum at least K
    Given an array arr[] of size N and an integer K > 0. The task is to find the number of subarrays with sum at least K.Examples: Input: arr[] = {6, 1, 2, 7}, K = 10 Output: 2 {6, 1, 2, 7} and {1, 2, 7} are the only valid subarrays.Input: arr[] = {3, 3, 3}, K = 5 Output: 3 Approach: For a fixed left
    6 min read
  • Count subarrays with sum as difference of squares of two numbers
    Given an array arr[], the task is to count all sub-array whose sum can be represented as the difference of squares of any two numbers. Examples: Input: arr[] = {1, 2, 3} Output: 4 Explanation: Required sub-arrays are {1}, {3}, {1, 2} and {2, 3} As 12 - 02 = 1, 22 - 12 = 3, 2+3=5=> 32 - 22 = 5 Inp
    6 min read
  • Count subarrays with non-zero sum in the given Array
    Given an array arr[] of size N, the task is to count the total number of subarrays for the given array arr[] which have a non-zero-sum.Examples: Input: arr[] = {-2, 2, -3} Output: 4 Explanation: The subarrays with non zero sum are: [-2], [2], [2, -3], [-3]. All possible subarray of the given input a
    7 min read
  • Count of Subarrays with sum equals k in given Binary Array
    Given a binary array arr[] and an integer k, the task is to find the count of non-empty subarrays with a sum equal to k. Examples: Input: arr[] = {1, 0, 1, 1, 0, 1}, k = 2Output: 6Explanation: All valid subarrays are: {1, 0, 1}, {0, 1, 1}, {1, 1}, {1, 0, 1}, {0, 1, 1, 0}, {1, 1, 0}. Input: arr[] = {
    10 min read
  • Count subarrays with equal number of 1's and 0's
    Given an array arr[] of size n containing 0 and 1 only. The problem is to count the subarrays having an equal number of 0's and 1's. Examples: Input: arr[] = {1, 0, 0, 1, 0, 1, 1}Output: 8Explanation: The index range for the 8 sub-arrays are: (0, 1), (2, 3), (0, 3), (3, 4), (4, 5)(2, 5), (0, 5), (1,
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences