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 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 => arr[0-1] => 1 + 2 = 3
arr[4] = 5 => arr[1-2] => 2 + 3 = 5
arr[5] = 6 => arr[0-2] => 1 + 2 + 3 = 6
arr[6] = 7 => arr[2-3] => 3 + 4 = 7

Input: arr[] = {1, 2, 3, 3}
Output: 2
There are 2 such elements in array –
arr[2] = 3 => arr[0-1] => 1 + 2 = 3
arr[3] = 3 => arr[0-1] => 1 + 2 = 3

Approach: The idea is to store the frequency of the elements of the array in a hash-map. Then, iterate over every possible subarray and check that its sum is present in the hash-map. If yes, then increment the count of such elements by its frequency.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to count the
// elements such that their exist
// a subarray whose sum is equal to
// this element
  
#include <bits/stdc++.h>
  
using namespace std;
  
// Function to count the elements
// such that their exist a subarray
// whose sum is equal to this element
int countElement(int arr[], int n)
{
    map<int, int> freq;
    int ans = 0;
  
    // Loop to count the frequency
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
  
    // Loop to iterate over every possible
    // subarray of the array
    for (int i = 0; i < n - 1; i++) {
        int tmpsum = arr[i];
        for (int j = i + 1; j < n; j++) {
            tmpsum += arr[j];
            if (freq.find(tmpsum) != freq.end()) {
                ans += freq[tmpsum];
            }
        }
    }
  
    return ans;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countElement(arr, n) << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to count the 
// elements such that their exist 
// a subarray whose sum is equal to 
// this element 
import java.util.*;
  
class GFG {
  
// Function to count the elements 
// such that their exist a subarray 
// whose sum is equal to this element
static int countElement(int arr[], int n)
{
    int freq[] = new int[n + 1];
    int ans = 0;
      
    // Loop to count the frequency 
    for(int i = 0; i < n; i++)
    {
       freq[arr[i]]++;
    }
  
    // Loop to iterate over every possible 
    // subarray of the array
    for(int i = 0; i < n - 1; i++)
    {
       int tmpsum = arr[i];
  
       for(int j = i + 1; j < n; j++)
       {
          tmpsum += arr[j];
  
          if (tmpsum <= n)
          {
              ans += freq[tmpsum];
              freq[tmpsum] = 0;
          }
       }
    }
      
    return ans;
}
  
// Driver Code
public static void main(String args[])
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.length;
    System.out.println(countElement(arr, n));
}
}
  
// This code is contributed by rutvik_56

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to count the
# elements such that their exist
# a subarray whose sum is equal to 
# this element
  
# Function to count element such 
# that their exist a subarray whose
# sum is equal to this element
def countElement(arr, n):
    freq = {}
    ans = 0
      
    # Loop to compute frequency
    # of the given elements
    for i in range(n):
        freq[arr[i]] = \
            freq.get(arr[i], 0) + 1
      
    # Loop to iterate over every 
    # possible subarray of array
    for i in range(n-1):
        tmpsum = arr[i]
        for j in range(i + 1, n):
            tmpsum += arr[j]
            if tmpsum in freq:
                ans += freq[tmpsum]
    return ans
           
   
# Driver Code
if __name__ == "__main__":
    arr =[1, 2, 3, 4, 5, 6, 7]
    n = len(arr)
    print(countElement(arr, n))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to count the 
// elements such that their exist 
// a subarray whose sum is equal to 
// this element 
using System;
  
class GFG {
  
// Function to count the elements 
// such that their exist a subarray 
// whose sum is equal to this element
static int countElement(int[] arr, int n)
{
    int[] freq = new int[n + 1];
    int ans = 0;
      
    // Loop to count the frequency 
    for(int i = 0; i < n; i++)
    {
       freq[arr[i]]++;
    }
  
    // Loop to iterate over every possible 
    // subarray of the array
    for(int i = 0; i < n - 1; i++)
    {
       int tmpsum = arr[i];
  
       for(int j = i + 1; j < n; j++)
       {
          tmpsum += arr[j];
            
          if (tmpsum <= n)
          {
              ans += freq[tmpsum];
              freq[tmpsum] = 0;
          }    
       }
    }
    return ans;
}
  
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.Length;
      
    Console.WriteLine(countElement(arr, n));
}
}
  
// This code is contributed by AbhiThakur

chevron_right


Output:

4

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.