Skip to content
Related Articles

Related Articles

Improve Article
Count of elements which is the sum of a subarray of the given Array
  • Difficulty Level : Expert
  • Last Updated : 14 May, 2021

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:
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:
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 their frequency.

Below is the implementation of the above approach:  



C++




// 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;
}

Java




// 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

Python3




# 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))

C#




// 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

Javascript




<script>
 
// Javascript implementation to count the
// elements such that their exist
// a subarray whose sum is equal to
// this element
 
// Function to count the elements
// such that their exist a subarray
// whose sum is equal to this element
function countElement(arr, n)
{
    let freq = Array.from({length: n+1}, (_, i) => 0);
    let ans = 0;
       
    // Loop to count the frequency
    for(let i = 0; i < n; i++)
    {
       freq[arr[i]]++;
    }
   
    // Loop to iterate over every possible
    // subarray of the array
    for(let i = 0; i < n - 1; i++)
    {
       let tmpsum = arr[i];
   
       for(let j = i + 1; j < n; j++)
       {
          tmpsum += arr[j];
   
          if (tmpsum <= n)
          {
              ans += freq[tmpsum];
              freq[tmpsum] = 0;
          }
       }
    }
       
    return ans;
}
 
// Driver Code
     
    let arr = [ 1, 2, 3, 4, 5, 6, 7 ];
    let n = arr.length;
    document.write(countElement(arr, n));
            
</script>
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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :