VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-unique-sub-array-sum-given-array/

⇱ Sum of unique sub-array sums - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of unique sub-array sums

Last Updated : 8 Jul, 2025

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.

[Naive Approach] - Sorting - O(n2 Log n) Time and O(n2) Space

  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.

Output
41

[Efficient Approach] - Hashing - O(n2) Time and O(n2) Space

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.


Output
41
Comment