Find sum of non-repeating (distinct) elements in an arrays in C++


Consider we have an array A with few elements. We have to find sum of all distinct elements in the array. So if the A = [5, 12, 63, 5, 33, 47, 12, 63], then sum of distinct elements is 160. Duplicate elements are simply ignored once it has considered.

We can use the unordered set to solve this problem efficiently. We will run one single for loop and which value comes first time, its add in sum variable and store in hash table that for next time, we will not use this value.

Example

 Live Demo

#include<iostream>
#include<unordered_set>
using namespace std;
int getNonRepeatSum(int arr[],int n) {
   int sum = 0;
   unordered_set< int > u_set;
   for (int i=0; i<n; i++) {
      if (u_set.find(arr[i]) == u_set.end()) {
         sum += arr[i];
         u_set.insert(arr[i]);
      }
   }
   return sum;
}
int main() {
   int arr[] = {5, 12, 63, 5, 33, 47, 12, 63};
   int n = sizeof(arr)/sizeof(int);
   cout << "Sum is: " << getNonRepeatSum(arr, n);
}

Output

Sum is: 160

Updated on: 18-Dec-2019

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements