Open In App

Find Sum of all unique sub-array sum for a given array.

Last Updated : 17 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. 

Note: Unique Sub-array sum means no other sub-array will have the same sum value. 

Examples:

Input : arr[] = {3, 4, 5} 
Output : 40 
Explanation: All possible unique sub-array with their sum are as: 
(3), (4), (5), (3+4), (4+5), (3+4+5). Here all are unique so required sum = 40

Input : arr[] = {2, 4, 2} 
Output : 12 
Explanation: All possible unique sub-array with their sum are as: 
(2), (4), (2), (2+4), (4+2), (2+4+2). Here only (4) and (2+4+2) are unique.

Method 1 (Sorting Based):

  1. Calculate the cumulative sum of an array. 
  2. Store all sub-array sum in vector. 
  3. Sort the vector. 
  4. Mark all duplicate sub-array sum to zero 
  5. Calculate and return totalSum.

Implementation:

C++




// C++ for finding sum of all unique
// subarray sum
#include <bits/stdc++.h>
using namespace std;
 
// function for finding grandSum
long long int findSubarraySum(int arr[], int n)
{
    int i, j;
 
    // calculate cumulative sum of array
    // cArray[0] will store sum of zero elements
    long long int cArray[n + 1] = { 0 };
    for (i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
    vector<long long int> subArrSum;
 
    // store all subarray sum in vector
    for (i = 1; i <= n; i++)
        for (j = i; j <= n; j++)
            subArrSum.push_back(cArray[j] -
                                cArray[i - 1]);
 
    // sort the vector
    sort(subArrSum.begin(), subArrSum.end());
 
    // mark all duplicate sub-array
    // sum to zero
    long long totalSum = 0;
    for (i = 0; i < subArrSum.size() - 1; i++)
    {
        if (subArrSum[i] == subArrSum[i + 1])
        {
            j = i + 1;
            while (subArrSum[j] == subArrSum[i] &&
                                   j < subArrSum.size())
            {
                subArrSum[j] = 0;
                j++;
            }
            subArrSum[i] = 0;
        }
    }
 
    // calculate total sum
    for (i = 0; i < subArrSum.size(); i++)
        totalSum += subArrSum[i];
 
    // return totalSum
    return totalSum;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findSubarraySum(arr, n);
    return 0;
}


Java




// Java for finding sum of all unique
// subarray sum
import java.util.*;
 
class GFG{
 
// Function for finding grandSum
static int findSubarraySum(int arr[], int n)
{
    int i, j;
 
    // Calculate cumulative sum of array
    // cArray[0] will store sum of zero elements
    int cArray[] = new int[n + 1];
    for(i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
    Vector<Integer> subArrSum = new Vector<Integer>();
 
    // Store all subarray sum in vector
    for(i = 1; i <= n; i++)
        for(j = i; j <= n; j++)
            subArrSum.add(cArray[j] -
                          cArray[i - 1]);
 
    // Sort the vector
    Collections.sort(subArrSum);
 
    // Mark all duplicate sub-array
    // sum to zero
    int totalSum = 0;
    for(i = 0; i < subArrSum.size() - 1; i++)
    {
        if (subArrSum.get(i) ==
            subArrSum.get(i + 1))
        {
            j = i + 1;
            while (subArrSum.get(j) ==
                   subArrSum.get(i) &&
               j < subArrSum.size())
            {
                subArrSum.set(j, 0);
                j++;
            }
            subArrSum.set(i, 0);
        }
    }
 
    // Calculate total sum
    for(i = 0; i < subArrSum.size(); i++)
        totalSum += subArrSum.get(i);
 
    // Return totalSum
    return totalSum;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = arr.length;
     
    System.out.print(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 for finding sum of all
# unique subarray sum
 
# function for finding grandSum
def findSubarraySum(arr, n):
     
    # calculate cumulative sum of array
    # cArray[0] will store sum of zero elements
    cArray = [0 for i in range(n + 1)]
    for i in range(0, n, 1):
        cArray[i + 1] = cArray[i] + arr[i]
 
    subArrSum = []
 
    # store all subarray sum in vector
    for i in range(1, n + 1, 1):
        for j in range(i, n + 1, 1):
            subArrSum.append(cArray[j] -
                             cArray[i - 1])
 
    # sort the vector
    subArrSum.sort(reverse = False)
 
    # mark all duplicate sub-array
    # sum to zero
    totalSum = 0
    for i in range(0, len(subArrSum) - 1, 1):
        if (subArrSum[i] == subArrSum[i + 1]):
            j = i + 1
            while (subArrSum[j] == subArrSum[i] and
                           j < len(subArrSum)):
                subArrSum[j] = 0
                j += 1
            subArrSum[i] = 0
 
    # calculate total sum
    for i in range(0, len(subArrSum), 1):
        totalSum += subArrSum[i]
 
    # return totalSum
    return totalSum
 
# Drivers code
if __name__ == '__main__':
    arr = [3, 2, 3, 1, 4]
    n = len(arr)
    print(findSubarraySum(arr, n))
     
# This code is contributed by
# Sahil_Shelangia


C#




// C# for finding sum of all unique
// subarray sum
using System;
using System.Collections.Generic;
class GFG{
 
// Function for finding grandSum
static int findSubarraySum(int []arr,
                           int n)
{
  int i, j;
 
  // Calculate cumulative sum
  // of array cArray[0] will
  // store sum of zero elements
  int []cArray = new int[n + 1];
   
  for(i = 0; i < n; i++)
    cArray[i + 1] = cArray[i] + arr[i];
 
  List<int> subArrSum = new List<int>();
 
  // Store all subarray sum in vector
  for(i = 1; i <= n; i++)
    for(j = i; j <= n; j++)
      subArrSum.Add(cArray[j] -
                    cArray[i - 1]);
 
  // Sort the vector
  subArrSum.Sort();
 
  // Mark all duplicate
  // sub-array sum to zero
  int totalSum = 0;
  for(i = 0; i < subArrSum.Count - 1; i++)
  {
    if (subArrSum[i] ==
        subArrSum[i + 1])
    {
      j = i + 1;
      while (subArrSum[j] ==
             subArrSum[i] &&
             j < subArrSum.Count)
      {
        subArrSum[j] = 0;
        j++;
      }
      subArrSum[i] = 0;
    }
  }
 
  // Calculate total sum
  for(i = 0; i < subArrSum.Count; i++)
    totalSum += subArrSum[i];
 
  // Return totalSum
  return totalSum;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = {3, 2, 3, 1, 4};
    int n = arr.Length;   
    Console.Write(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
      // JavaScript for finding sum of all unique
      // subarray sum
      // Function for finding grandSum
      function findSubarraySum(arr, n) {
        var i, j;
 
        // Calculate cumulative sum
        // of array cArray[0] will
        // store sum of zero elements
        var cArray = new Array(n + 1).fill(0);
 
        for (i = 0; i < n; i++)
        cArray[i + 1] = cArray[i] + arr[i];
 
        var subArrSum = [];
 
        // Store all subarray sum in vector
        for (i = 1; i <= n; i++)
          for (j = i; j <= n; j++) subArrSum.push(cArray[j] - cArray[i - 1]);
 
        // Sort the vector
        subArrSum.sort();
 
        // Mark all duplicate
        // sub-array sum to zero
        var totalSum = 0;
        for (i = 0; i < subArrSum.length - 1; i++) {
          if (subArrSum[i] == subArrSum[i + 1]) {
            j = i + 1;
            while (subArrSum[j] == subArrSum[i] && j < subArrSum.length) {
              subArrSum[j] = 0;
              j++;
            }
            subArrSum[i] = 0;
          }
        }
 
        // Calculate total sum
        for (i = 0; i < subArrSum.length; i++) totalSum += subArrSum[i];
 
        // Return totalSum
        return totalSum;
      }
 
      // Driver Code
      var arr = [3, 2, 3, 1, 4];
      var n = arr.length;
      document.write(findSubarraySum(arr, n));
       
      // This code is contributed by rdtank.
    </script>


Output

41

Complexity Analysis:

  • Time Complexity: O(N^2 + N * logN)
  • Auxiliary Space: O(N)

Method 2 (Hashing Based): 

The idea is to make an empty hash table. We generate all subarrays. For every subarray, we compute its sum and increment count of the sum in the hash table. Finally, we add all those sums whose count is 1.

Implementation:

C++




// C++ for finding sum of all unique subarray sum
#include <bits/stdc++.h>
using namespace std;
 
// function for finding grandSum
long long int findSubarraySum(int arr[], int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    unordered_map<int, int> m;
    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = i; j < n; j++) {
            sum += arr[j];
            m[sum]++;
        }
    }
 
    // Print all those sums that appear
    // once.
    for (auto x : m)
        if (x.second == 1)
            res += x.first;
 
    return res;
}
 
// Driver code
int main()
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findSubarraySum(arr, n);
    return 0;
}


Java




// Java for finding sum of all
// unique subarray sum
import java.util.*;
 
class GFG
{
 
// function for finding grandSum
static int findSubarraySum(int []arr, int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    HashMap<Integer,
            Integer> m = new HashMap<Integer,
                                     Integer>();
    for (int i = 0; i < n; i++)
    {
        int sum = 0;
        for (int j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.containsKey(sum))
            {
                m.put(sum, m.get(sum) + 1);
            }
            else
            {
                m.put(sum, 1);
            }
        }
    }
 
    // Print all those sums that appear
    // once.
    for (Map.Entry<Integer,
                   Integer> x : m.entrySet())
        if (x.getValue() == 1)
            res += x.getKey();
 
    return res;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 2, 3, 1, 4 };
    int n = arr.length;
    System.out.println(findSubarraySum(arr, n));
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Python3 for finding sum of all
# unique subarray sum
 
# function for finding grandSum
def findSubarraySum(arr, n):
 
    res = 0
 
    # Go through all subarrays, compute sums
    # and count occurrences of sums.
    m = dict()
    for i in range(n):
        Sum = 0
        for j in range(i, n):
            Sum += arr[j]
            m[Sum] = m.get(Sum, 0) + 1
         
    # Print all those Sums that appear
    # once.
    for x in m:
        if m[x] == 1:
            res += x
 
    return res
 
# Driver code
arr = [3, 2, 3, 1, 4]
n = len(arr)
print(findSubarraySum(arr, n))
 
# This code is contributed by mohit kumar


C#




// C# for finding sum of all
// unique subarray sum
using System;
using System.Collections.Generic;
     
class GFG
{
 
// function for finding grandSum
static int findSubarraySum(int []arr, int n)
{
    int res = 0;
 
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    Dictionary<int,
               int> m = new Dictionary<int,
                                       int>();
    for (int i = 0; i < n; i++)
    {
        int sum = 0;
        for (int j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.ContainsKey(sum))
            {
                m[sum] = m[sum] + 1;
            }
            else
            {
                m.Add(sum, 1);
            }
        }
    }
 
    // Print all those sums that appear
    // once.
    foreach(KeyValuePair<int, int> x in m)
        if (x.Value == 1)
            res += x.Key;
 
    return res;
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 2, 3, 1, 4 };
    int n = arr.Length;
    Console.WriteLine(findSubarraySum(arr, n));
}
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Javascript for finding sum of all
// unique subarray sum
 
// Function for finding grandSum
function findSubarraySum(arr, n)
{
    let res = 0;
     
    // Go through all subarrays, compute sums
    // and count occurrences of sums.
    let m = new Map();
    for(let i = 0; i < n; i++)
    {
        let sum = 0;
        for(let j = i; j < n; j++)
        {
            sum += arr[j];
            if (m.has(sum))
            {
                m.set(sum, m.get(sum) + 1);
            }
            else
            {
                m.set(sum, 1);
            }
        }
    }
     
    // Print all those sums that appear
    // once.
    for(let x of m)
        if (x[1] == 1)
            res += x[0];
     
    return res;
}
 
// Driver code
let arr = [ 3, 2, 3, 1, 4 ];
let n = arr.length;
 
document.write(findSubarraySum(arr, n));
 
// This code is contributed by gfgking
 
</script>


Output

41

Complexity Analysis:

  • Time Complexity: O(N^2)
  • Auxiliary Space: O(N)


Previous Article
Next Article

Similar Reads

Count the number of sub-arrays such that the average of elements present in the sub-array is greater than that not present in the sub-array
Given an array of integers arr[], the task is to count the number of sub-arrays such that the average of elements present in the sub-array is greater than the average of elements that are not present in the sub-array.Examples: Input: arr[] = {6, 3, 5} Output: 3 The sub-arrays are {6}, {5} and {6, 3, 5} because their averages are greater than {3, 5}
8 min read
Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
Given a string str, its sub-strings are formed in such a way that all the sub-strings starting with the first character of the string will occur first in the sorted order of their lengths followed by all the sub-strings starting with the second character of the string in the sorted order of their lengths and so on. For example for the string abc, i
9 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and arr[x + 1]. Examples: Input: arr[] = {4, 5, 6, 7, 8
9 min read
Find minimum length sub-array which has given sub-sequence in it
Given an array arr[] of N elements, the task is to find the length of the smallest sub-array which has the sequence {0, 1, 2, 3, 4} as a sub-sequence in it. Examples: Input: arr[] = {0, 1, 2, 3, 4, 2, 0, 3, 4} Output: 5 The required Subarray is {0, 1, 2, 3, 4} with minimum length. The entire array also includes the sequence but it is not minimum in
10 min read
Find the maximum element in the array other than A<sub>i</sub>
Given an array arr[] of size N. The task is to find maximum element among N - 1 elements other than arr[i] for each i from 1 to N.Examples: Input: arr[] = {2, 5, 6, 1, 3} Output: 6 6 5 6 6 Input: arr[] = {1, 2, 3} Output: 3 3 2 Approach: An efficient approach is to make prefix and suffix array of maximum elements and find maximum element among N -
6 min read
Maximum number of Unique integers in Sub-Array of given size
Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M. Examples: Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5, 3, 5)- Has 2 unique numbers. s2 = (3, 5, 2)- Has
12 min read
Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
Give an integer array arr[] consisting of elements from the set {0, 1}. The task is to print the number of ways the array can be divided into sub-arrays such that each sub-array contains exactly one 1. Examples: Input: arr[] = {1, 0, 1, 0, 1} Output: 4 Below are the possible ways: {1, 0}, {1, 0}, {1}{1}, {0, 1, 0}, {1}{1, 0}, {1}, {0, 1}{1}, {0, 1}
6 min read
Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read
Divide the array into minimum number of sub-arrays having unique elements
Given an array arr. The task is to divide the array into the minimum number of subarrays containing unique elements and return the count of such subarrays. Note: An array element cannot be present in more than one subarray.Examples : Input : arr[] = {1, 2, 1, 1, 2, 3}Output : 3Explanation : The subarrays having unique elements are { 1, 2 }, { 1 },
8 min read
Article Tags :
Practice Tags :