Find sum of non-repeating (distinct) elements in an array - GeeksforGeeks

24 May, 2021
Given an integer array with repeated elements, the task is to find sum of all distinct elements in array.Examples: 
Input  : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};
Output : 78
Here we take 12, 10, 9, 45, 2 for sum
because it's distinct elements 

Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};
Output : 71
A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on left side of it. If present, then ignores the element.Time Complexity : O(n2) Auxiliary Space : O(1)A Better Solution of this problem is that using sorting technique we firstly sort all elements of array in ascending order and and find one by one distinct elements in array.  
C++
Java
Python3
C#
Javascript
// C++ Find the sum of all non-repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[], int n){    // sort all elements of array    sort(arr, arr + n);     int sum = 0;    for (int i=0; i<n; i++)    {        if (arr[i] != arr[i+1])            sum = sum + arr[i];    }     return sum;} // Driver codeint main(){    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};    int n = sizeof(arr)/sizeof(int);    cout << findSum(arr, n);    return 0;}
import java.util.Arrays; // Java Find the sum of all non-repeated// elements in an arraypublic class GFG { // Find the sum of all non-repeated elements// in an array    static int findSum(int arr[], int n) {        // sort all elements of array         Arrays.sort(arr);                int sum = arr[0];        for (int i = 0; i < n-1; i++) {            if (arr[i] != arr[i + 1]) {                sum = sum + arr[i+1];            }        }         return sum;    } // Driver code    public static void main(String[] args) {        int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};        int n = arr.length;        System.out.println(findSum(arr, n));     }}
     # Python3 Find the sum of all non-repeated# elements in an array   # Find the sum of all non-repeated elements# in an arraydef findSum(arr,  n):    # sort all elements of array    arr.sort()      sum = arr[0]    for i in range(0,n-1):        if (arr[i] != arr[i+1]):            sum = sum + arr[i+1]         return sum  # Driver codedef main():    arr= [1, 2, 3, 1, 1, 4, 5, 6]    n = len(arr)    print(findSum(arr, n)) if __name__ == '__main__':    main()# This code is contributed by 29AjayKumar
// C# Find the sum of all non-repeated// elements in an arrayusing System;class GFG{     // Find the sum of all non-repeated elements    // in an array    static int findSum(int []arr, int n)    {        // sort all elements of array        Array.Sort(arr);                 int sum = arr[0];        for (int i = 0; i < n - 1; i++)        {            if (arr[i] != arr[i + 1])            {                sum = sum + arr[i + 1];            }        }        return sum;    }     // Driver code    public static void Main()    {        int []arr = {1, 2, 3, 1, 1, 4, 5, 6};        int n = arr.Length;        Console.WriteLine(findSum(arr, n));    }} // This code is contributed by 29AjayKumar
<script> // JavaScript Program to find the sum of all non-repeated// elements in an array // Find the sum of all non-repeated elements// in an arrayfunction findSum(arr, n){    // sort all elements of array    arr.sort();     let sum = 0;    for (let i=0; i<n; i++)    {        if (arr[i] != arr[i+1])            sum = sum + arr[i];    }     return sum;} // Driver code     let arr = [1, 2, 3, 1, 1, 4, 5, 6];    let n = arr.length;    document.write(findSum(arr, n)); // This code is contributed by Surbhi Tyagi </script>
Output: 
21
Time Complexity : O(n log n) Space Complexity : O(1)An Efficient solution of this problem is that using unordered_set we run a single for loop and which value comes first time its add in sum variable and store in hash table that for next time we not use this value. 
C++
Java
Python3
C#
Javascript
// C++ Find the sum of all non- repeated// elements in an array#include<bits/stdc++.h>using namespace std; // Find the sum of all non-repeated elements// in an arrayint findSum(int arr[],int n){    int sum = 0;     // Hash to store all element of array    unordered_set< int > s;    for (int i=0; i<n; i++)    {        if (s.find(arr[i]) == s.end())        {            sum += arr[i];            s.insert(arr[i]);        }    }     return sum;} // Driver codeint main(){    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};    int n = sizeof(arr)/sizeof(int);    cout << findSum(arr, n);    return 0;}
// Java Find the sum of all non- repeated// elements in an arrayimport java.util.*; class GFG{         // Find the sum of all non-repeated elements    // in an array    static int findSum(int arr[], int n)    {        int sum = 0;         // Hash to store all element of array        HashSet<Integer> s = new HashSet<Integer>();        for (int i = 0; i < n; i++)        {            if (!s.contains(arr[i]))            {                sum += arr[i];                s.add(arr[i]);            }        }        return sum;    }     // Driver code    public static void main(String[] args)    {        int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};        int n = arr.length;        System.out.println(findSum(arr, n));    }} // This code is contributed by Rajput-Ji
# Python3 Find the sum of all# non- repeated elements in an array # Find the sum of all non-repeated# elements in an arraydef findSum(arr, n):    s = set()    sum = 0     # Hash to store all element    # of array    for i in range(n):        if arr[i] not in s:            s.add(arr[i])    for i in s:        sum = sum + i     return sum # Driver codearr = [1, 2, 3, 1, 1, 4, 5, 6]n = len(arr)print(findSum(arr, n)) # This code is contributed by Shrikant13
// C# Find the sum of all non- repeated// elements in an arrayusing System;using System.Collections.Generic; class GFG{         // Find the sum of all non-repeated elements    // in an array    static int findSum(int []arr, int n)    {        int sum = 0;         // Hash to store all element of array        HashSet<int> s = new HashSet<int>();        for (int i = 0; i < n; i++)        {            if (!s.Contains(arr[i]))            {                sum += arr[i];                s.Add(arr[i]);            }        }        return sum;    }     // Driver code    public static void Main(String[] args)    {        int []arr = {1, 2, 3, 1, 1, 4, 5, 6};        int n = arr.Length;        Console.WriteLine(findSum(arr, n));    }} // This code is contributed by Rajput-Ji
<script> //  Javascript program Find the sum of all non- repeated// elements in an array     // Find the sum of all non-repeated elements    // in an array    function findSum(arr, n)    {        let sum = 0;          // Hash to store all element of array        let s = new Set();        for (let i = 0; i < n; i++)        {            if (!s.has(arr[i]))            {                sum += arr[i];                s.add(arr[i]);            }        }        return sum;    }         // Driver code         let arr = [1, 2, 3, 1, 1, 4, 5, 6];        let n = arr.length;        document.write(findSum(arr, n));     </script>
Output:  
21
Time Complexity: O(n) Auxiliary Space: O(n) 
Method #3:Using Built-in python functions:
Approach:
Calculate the frequencies using Counter() function
Convert the frequency keys to the list.
Calculate the sum of the list.
Below is the implementation of the above approach.
Python3
# Python program for the above approachfrom collections import Counter # Function to return the sum of distinct elementsdef sumOfElements(arr, n):     # Counter function is used to    # calculate frequency of elements of array    freq = Counter(arr)         # Converting keys of freq dictionary to list    lis = list(freq.keys())         # Return sum of list    return sum(lis)  # Driver codeif __name__ == "__main__":     arr = [1, 2, 3, 1, 1, 4, 5, 6]    n = len(arr)     print(sumOfElements(arr, n)) # This code is contributed by vikkycirus
Output:
21
This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
princiraj1992
29AjayKumar
Rajput-Ji
SachinDiwakar1
surbhityagi15
vikkycirus
avijitmondal1998
Oxigen Wallet
Arrays
Hash
Sorting
Oxigen Wallet
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)