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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count of Subarrays with sum equals k in given Binary Array
Next article icon

Count subarrays with non-zero sum in the given Array

Last Updated : 13 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 array are [-2], [2], [-3], [2, -2], [2, -3], [-2, 2, -3]. Out of these [2, -2] is not included in the count because 2+(-2) = 0 and [-2, 2, -3] is not selected because one the subarray [2, -2] of this array has a zero sum of elements.
Input: arr[] = {1, 3, -2, 4, -1} 
Output: 15 
Explanation: 
There are 15 subarray for the given array {1, 3, -2, 4, -1} which has a non zero sum.

Approach:
The main idea to solve the above question is to use the Prefix Sum Array and Map Data Structure.

  • First, build the Prefix sum array of the given array and use the below formula to check if the subarray has 0 sum of elements.

Sum of Subarray[L, R] = Prefix[R] – Prefix[L – 1]. So, If Sum of Subarray[L, R] = 0
Then, Prefix[R] – Prefix[L – 1] = 0. Hence, Prefix[R] = Prefix[L – 1] 
 

  • Now, iterate from 1 to N and keep a Hash table for storing the index of the previous occurrence of the element and a variable let’s say last, and initialize it to 0.
  • Check if Prefix[i] is already present in the Hash or not. If yes then, update last as last = max(last, hash[Prefix[i]] + 1). Otherwise, Add i – last to the answer and update the Hash table.

Below is the implementation of the above approach:

C++




// C++ program to Count the total number of
// subarrays for a given array such that its
// subarray should have non zero sum
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to build the Prefix sum array
vector<int> PrefixSumArray(int arr[], int n)
{
    vector<int> prefix(n);
 
    // Store prefix of the first position
    prefix[0] = arr[0];
 
    for (int i = 1; i < n; i++)
        prefix[i] = prefix[i - 1] + arr[i];
 
    return prefix;
}
 
// Function to return the Count of
// the total number of subarrays
int CountSubarray(int arr[], int n)
{
    vector<int> Prefix(n);
 
    // Calculating the prefix array
    Prefix = PrefixSumArray(arr, n);
 
    int last = 0, ans = 0;
 
    map<int, int> Hash;
 
    Hash[0] = -1;
 
    for (int i = 0; i <= n; i++) {
        // Check if the element already exists
        if (Hash.count(Prefix[i]))
            last = max(last, Hash[Prefix[i]] + 1);
 
        ans += max(0, i - last);
 
        // Mark the element
        Hash[Prefix[i]] = i;
    }
 
    // Return the final answer
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 3, -2, 4, -1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << CountSubarray(arr, N);
}
 
 

Java




// Java program to count the total number of
// subarrays for a given array such that its
// subarray should have non zero sum
import java.util.*;
 
class GFG{
 
// Function to build the Prefix sum array
static int[] PrefixSumArray(int arr[], int n)
{
    int []prefix = new int[n];
     
    // Store prefix of the first position
    prefix[0] = arr[0];
 
    for(int i = 1; i < n; i++)
        prefix[i] = prefix[i - 1] + arr[i];
 
    return prefix;
}
 
// Function to return the Count of
// the total number of subarrays
static int CountSubarray(int arr[], int n)
{
    int []Prefix = new int[n];
 
    // Calculating the prefix array
    Prefix = PrefixSumArray(arr, n);
 
    int last = 0, ans = 0;
 
    HashMap<Integer,
            Integer> Hash = new HashMap<Integer,
                                        Integer>();
 
    Hash.put(0, -1);
 
    for(int i = 0; i <= n; i++)
    {
         
        // Check if the element already exists
        if (i < n && Hash.containsKey(Prefix[i]))
            last = Math.max(last,
                            Hash.get(Prefix[i]) + 1);
 
        ans += Math.max(0, i - last);
 
        // Mark the element
        if (i < n)
        Hash.put(Prefix[i], i);
    }
 
    // Return the final answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 3, -2, 4, -1 };
 
    int N = arr.length;
 
    System.out.print(CountSubarray(arr, N));
}
}
 
// This code is contributed by amal kumar choubey
 
 

Python3




# Python3 program to count the total number 
# of subarrays for a given array such that
# its subarray should have non zero sum
 
# Function to build the prefix sum array
def PrefixSumArray(arr, n):
 
    prefix = [0] * (n + 1);
 
    # Store prefix of the first position
    prefix[0] = arr[0];
 
    for i in range(1, n):
        prefix[i] = prefix[i - 1] + arr[i];
         
    return prefix;
 
# Function to return the count of
# the total number of subarrays
def CountSubarray(arr, n):
 
    Prefix = [0] * (n + 1);
 
    # Calculating the prefix array
    Prefix = PrefixSumArray(arr, n);
 
    last = 0; ans = 0;
 
    Hash = {};
 
    Hash[0] = -1;
 
    for i in range(n + 1):
         
        # Check if the element already exists
        if (Prefix[i] in Hash):
            last = max(last, Hash[Prefix[i]] + 1);
 
        ans += max(0, i - last);
 
        # Mark the element
        Hash[Prefix[i]] = i;
 
    # Return the final answer
    return ans;
 
# Driver code
if __name__ == "__main__" :
 
    arr = [ 1, 3, -2, 4, -1 ];
    N = len(arr);
 
    print(CountSubarray(arr, N));
     
# This code is contributed by AnkitRai01
 
 

C#




// C# program to count the total number of
// subarrays for a given array such that its
// subarray should have non zero sum
using System;
using System.Collections.Generic;
class GFG{
 
// Function to build the Prefix sum array
static int[] PrefixSumArray(int []arr, int n)
{
    int []prefix = new int[n];
     
    // Store prefix of the first position
    prefix[0] = arr[0];
 
    for(int i = 1; i < n; i++)
        prefix[i] = prefix[i - 1] + arr[i];
    return prefix;
}
 
// Function to return the Count of
// the total number of subarrays
static int CountSubarray(int []arr, int n)
{
    int []Prefix = new int[n];
 
    // Calculating the prefix array
    Prefix = PrefixSumArray(arr, n);
 
    int last = 0, ans = 0;
    Dictionary<int,
               int> Hash = new Dictionary<int,
                                          int>();
    Hash.Add(0, -1);
    for(int i = 0; i <= n; i++)
    {       
        // Check if the element already exists
        if (i < n && Hash.ContainsKey(Prefix[i]))
            last = Math.Max(last,
                            Hash[Prefix[i]] + 1);
 
        ans += Math.Max(0, i - last);
 
        // Mark the element
        if (i < n)
        Hash.Add(Prefix[i], i);
    }
 
    // Return the readonly answer
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = {1, 3, -2, 4, -1};
    int N = arr.Length;
    Console.Write(CountSubarray(arr, N));
}
}
 
// This code is contributed by shikhasingrajput
 
 

Javascript




<script>
 
// Javascript program to count the total number of
// subarrays for a given array such that its
// subarray should have non zero sum
 
// Function to build the Prefix sum array
function PrefixSumArray(arr, n)
{
    let prefix = Array.from({length: n}, (_, i) => 0);
      
    // Store prefix of the first position
    prefix[0] = arr[0];
  
    for(let i = 1; i < n; i++)
        prefix[i] = prefix[i - 1] + arr[i];
  
    return prefix;
}
  
// Function to return the Count of
// the total number of subarrays
function CountSubarray(arr, n)
{
    let Prefix = Array.from({length: n}, (_, i) => 0);
  
    // Calculating the prefix array
    Prefix = PrefixSumArray(arr, n);
  
    let last = 0, ans = 0;
  
    let Hash = new Map();
  
    Hash.set(0, -1);
  
    for(let i = 0; i <= n; i++)
    {
          
        // Check if the element already exists
        if (i < n && Hash.has(Prefix[i]))
            last = Math.max(last,
                            Hash.get(Prefix[i]) + 1);
  
        ans += Math.max(0, i - last);
  
        // Mark the element
        if (i < n)
        Hash.set(Prefix[i], i);
    }
  
    // Return the final answer
    return ans;
}
 
// Driver code
     
      let arr = [ 1, 3, -2, 4, -1 ];
  
    let N = arr.length;
  
    document.write(CountSubarray(arr, N));
  
 // This code is contributed by code_hunt.
</script>
 
 
Output: 
15

 

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



Next Article
Count of Subarrays with sum equals k in given Binary Array

H

harshit23
Improve
Article Tags :
  • Arrays
  • Data Structures
  • DSA
  • Hash
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Data Structures
  • Hash

Similar Reads

  • 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
  • 3 Sum - Count Triplets With Given Sum In Sorted Array
    Given a sorted array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k. Exam
    10 min read
  • Count of elements which is the sum of a subarray of the given Array
    Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
    7 min read
  • Count of Subarrays of given Array with median at least X
    Given an array arr[]of integers with length N and an integer X, the task is to calculate the number of subarrays with median greater than or equal to the given integer X. Examples: Input: N=4, A = [5, 2, 4, 1], X = 4Output: 7Explanation: For subarray [5], median is 5. (>= 4)For subarray [5, 2], m
    9 min read
  • Count of subarrays with digit sum equals to X
    Given an array arr[] of length N and integer X, the task is to count no of subarrays having digit sum equal to X. Examples: Input: arr[] = {10, 5, 13, 20, 9}, X = 6Output: 2Explanation: There are two subarrays which is having digit sum equal to 6. {10, 5} => (1 + 0) + 5 = 6 and {13 , 20} => (1
    9 min read
  • Count Subarrays With Sum Divisible By K
    Given an array arr[] and an integer k, the task is to count all subarrays whose sum is divisible by k. Examples: Input: arr[] = [4, 5, 0, -2, -3, 1], k = 5Output: 7Explanation: There are 7 subarrays whose sum is divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and
    9 min read
  • 2 Sum - Count Pairs with given Sum in Sorted Array
    Given a sorted array arr[] and an integer target, the task is to find the number of pairs in the array whose sum is equal to target. Examples: Input: arr[] = [-1, 1, 5, 5, 7], target = 6Output: 3Explanation: Pairs with sum 6 are (1, 5), (1, 5) and (-1, 7). Input: arr[] = [1, 1, 1, 1], target = 2Outp
    9 min read
  • Count maximum non-overlapping subarrays with given sum
    Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
    7 min read
  • Count Subarrays with given XOR
    Given an array of integers arr[] and a number k, the task is to count the number of subarrays having XOR of their elements as k. Examples: Input: arr[] = [4, 2, 2, 6, 4], k = 6Output: 4Explanation: The subarrays having XOR of their elements as 6 are [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], and [6].Input:
    10 min read
  • Print all subarrays with sum in a given range
    Given an array arr[] of positive integers and two integers L and R defining the range [L, R]. The task is to print the subarrays having sum in the range L to R. Examples: Input: arr[] = {1, 4, 6}, L = 3, R = 8Output: {1, 4}, {4}, {6}.Explanation: All the possible subarrays are the following{1] with
    5 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