Open In App

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the 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
Recommended Practice

Naive Approach:

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 right side of it. If present, then ignores the element.

Steps that were to follow the above approach:

  • Make a variable sum and initialize it with 0. It is the variable that will contain the final answer
  • Now traverse the input array
  • While traversing the array pick an element and check all elements to its right by running an inner loop.
  • If we get any element with the same value as that element then stop the inner loop
  • If any element exists to the right of that element that has the same value then it is ok else add the value of that element to the sum.

Code to implement the above approach:

C++




// 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 array
int findSum(int arr[], int n)
{
    //Intialized a variable with 0 to contain final answer
    int sum = 0;
    
    //Traverse the input array
    for (int i=0; i<n; i++)
    {
        int j=i+1;
        while(j<n){
            //if any element present on the right of arr[i] that has 
            //same value as arr[i] then break the loop
            if(arr[j]==arr[i]){break;}
            j++;
        }
        //If no such element exists then add this element's value into sum
        if(j==n){sum+=arr[i];}
    }
      
  //Finally return the answer
    return sum;
}
  
// Driver code
int main()
{
    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
    int n = sizeof(arr)/sizeof(int);
    cout << findSum(arr, n);
    return 0;
}


Java




import java.util.Arrays;
  
public class Main {
  
  // Find the sum of all non-repeated elements
  // in an array
  public static int findSum(int arr[], int n) 
  {
  
    // Intialize a variable with 0 to contain final answer
    int sum = 0;
  
    // Traverse the input array
    for (int i = 0; i < n; i++) {
      int j = i + 1;
      while (j < n) 
      {
  
        // If any element present on the right of arr[i] that has 
        // same value as arr[i], then break the loop
        if (arr[j] == arr[i]) {
          break;
        }
        j++;
      }
  
      // If no such element exists then add this element's value into sum
      if (j == n) {
        sum += arr[i];
      }
    }
  
    // Finally return the answer
    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
  
  
def findSum(arr):
    # Initialize a variable with 0 to contain final answer
    sum = 0
  
    # Traverse the input array
    for i in range(len(arr)):
        j = i + 1
        while j < len(arr):
            # If any element present on the right of arr[i] that has
            # same value as arr[i] then break the loop
            if arr[j] == arr[i]:
                break
            j += 1
        # If no such element exists then add this element's value into sum
        if j == len(arr):
            sum += arr[i]
  
    # Finally return the answer
    return sum
  
  
# Driver code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
print(findSum(arr))


C#




// C# code to find the sum of all non-repeated
// elements in an array
using System;
  
public class GFG {
    
    // Find the sum of all non-repeated elements
    // in an array
    public static int FindSum(int[] arr, int n)
    {
        // Initialized a variable with 0 to contain final
        // answer
        int sum = 0;
        
        // Traverse the input array
        for (int i = 0; i < n; i++) {
            int j = i + 1;
            while (j < n) {
                // if any element present on the right of
                // arr[i] that has same value as arr[i] then
                // break the loop
                if (arr[j] == arr[i]) {
                    break;
                }
                j++;
            }
            // If no such element exists then add this
            // element's value into sum
            if (j == n) {
                sum += arr[i];
            }
        }
  
        // Finally return the answer
        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));
    }
}


Javascript




// JavaScript 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) {
// Intialize a variable with 0 to contain final answer
let sum = 0;
  
// Traverse the input array
for (let i=0; i<arr.length; i++) {
let j=i+1;
while(j<arr.length){
// If any element present on the right of arr[i] that has
// same value as arr[i] then break the loop
if(arr[j]==arr[i]){break;}
j++;
}
// If no such element exists then add this element's value into sum
if(j==arr.length){sum+=arr[i];}
}
  
// Finally return the answer
return sum;
}
  
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
console.log(findSum(arr));


Output-

21

Time Complexity : O(n2,because of two nested loop
Auxiliary Space : O(1) , because no extra space has been used

A Better Solution of this problem is that using sorting technique we firstly sort all elements of array in ascending order and find one by one distinct elements in array. 

Implementation:

C++




// 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 array
int 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 code
int main()
{
    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
    int n = sizeof(arr)/sizeof(int);
    cout << findSum(arr, n);
    return 0;
}


Java




import java.util.Arrays;
  
// Java Find the sum of all non-repeated 
// elements in an array 
public 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




      
# Python3 Find the sum of all non-repeated
# elements in an array
  
   
# Find the sum of all non-repeated elements
# in an array
def 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 code
def 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#




// C# Find the sum of all non-repeated 
// elements in an array 
using 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


Javascript




<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 array 
function 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) 
Auxiliary Space : O(1)

An Efficient solution to this problem is that using unordered_set we run a single for loop and in which the value comes the first time it’s an add-in sum variable and stored in a hash table that for the next time we do not use this value.

Implementation:

C++




// 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 array
int 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 code
int main()
{
    int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
    int n = sizeof(arr)/sizeof(int);
    cout << findSum(arr, n);
    return 0;
}


Java




// Java Find the sum of all non- repeated 
// elements in an array 
import 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




# Python3 Find the sum of all 
# non- repeated elements in an array 
  
# Find the sum of all non-repeated
# elements in an array
def 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 code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
  
# This code is contributed by Shrikant13


C#




// C# Find the sum of all non- repeated 
// elements in an array 
using 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


Javascript




<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 and javascript functions:

Approach for python:

  • Calculate the frequencies using Counter() function
  • Convert the frequency keys to the list.
  • Calculate the sum of the list.

Approach for Javascript:

  • The Counter function from the collections module in Python has been replaced with an empty object.
  • The keys() method is used to extract the keys of the object as an array.
  • The reduce() method is used to calculate the sum of the array.

Below is the implementation of the above approach.

C++




// c++ program for the above approach
#include <iostream>
#include <unordered_map>
#include <vector>
  
using namespace std;
  
// Function to return the sum of distinct elements
int sumOfElements(vector<int> arr, int n) {
  
  // Creating an unordered_map to store the frequency of each element
  unordered_map<int, int> freq;
  
  for(int i=0; i<n; i++) {
    freq[arr[i]]++;
  }
  
  // Creating a vector to store the unique elements
  vector<int> lis;
  
  for(auto it=freq.begin(); it!=freq.end(); it++) {
    lis.push_back(it->first);
  }
  
  // Calculating the sum of unique elements
  int sum = 0;
  for(int i=0; i<lis.size(); i++) {
    sum += lis[i];
  }
  
  return sum;
}
  
// Driver code
int main() {
  
  vector<int> arr = {1, 2, 3, 1, 1, 4, 5, 6};
  int n = arr.size();
  
  cout << sumOfElements(arr, n);
  
  return 0;
}
  
// This code is contributed by Prince Kumar


Java




// Java program for the above approach
  
import java.util.*;
  
public class Main {
    
  // Function to return the sum of distinct elements
  public static int sumOfElements(List<Integer> arr, int n) {
  
    // Creating a HashMap to store the frequency of each element
    HashMap<Integer, Integer> freq = new HashMap<>();
  
    for(int i=0; i<n; i++) {
      freq.put(arr.get(i), freq.getOrDefault(arr.get(i), 0) + 1);
    }
  
    // Creating a list to store the unique elements
    List<Integer> lis = new ArrayList<>();
  
    for(Map.Entry<Integer, Integer> entry : freq.entrySet()) {
      lis.add(entry.getKey());
    }
  
    // Calculating the sum of unique elements
    int sum = 0;
    for(int i=0; i<lis.size(); i++) {
      sum += lis.get(i);
    }
  
    return sum;
  }
  
  // Driver code
  public static void main(String[] args) {
  
    List<Integer> arr = Arrays.asList(1, 2, 3, 1, 1, 4, 5, 6);
    int n = arr.size();
  
    System.out.println(sumOfElements(arr, n));
  }
}
  
// This code is contributed by adityashatmfh


Python3




# Python program for the above approach
from collections import Counter
  
# Function to return the sum of distinct elements
  
  
def 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 code
if __name__ == "__main__":
  
    arr = [1, 2, 3, 1, 1, 4, 5, 6]
    n = len(arr)
  
    print(sumOfElements(arr, n))
  
# This code is contributed by vikkycirus


C#




using System;
using System.Collections.Generic;
using System.Linq;
  
public class Program
{
    // Function to return the sum of distinct elements
    public static int SumOfElements(List<int> arr, int n)
    {
        // Creating a Dictionary to store the frequency of each element
        Dictionary<int, int> freq = new Dictionary<int, int>();
  
        for (int i = 0; i < n; i++)
        {
            if (freq.ContainsKey(arr[i]))
                freq[arr[i]]++;
            else
                freq[arr[i]] = 1;
        }
  
        // Creating a list to store the unique elements
        List<int> lis = new List<int>();
  
        foreach (KeyValuePair<int, int> entry in freq)
        {
            lis.Add(entry.Key);
        }
  
        // Calculating the sum of unique elements
        int sum = 0;
        for (int i = 0; i < lis.Count; i++)
        {
            sum += lis[i];
        }
  
        return sum;
    }
  
    // Driver code
    public static void Main(string[] args)
    {
        List<int> arr = new List<int> { 1, 2, 3, 1, 1, 4, 5, 6 };
        int n = arr.Count;
  
        Console.WriteLine(SumOfElements(arr, n));
    }
}


Javascript




// JavaScript program for the above approach
function sumOfElements(arr, n) {
  
    // Creating an empty object
    let freq = {};
      
    // Loop to create frequency object
    for(let i = 0; i < n; i++) {
        freq[arr[i]] = (freq[arr[i]] || 0) + 1;
    }
      
    // Converting keys of freq object to array
    let lis = Object.keys(freq).map(Number);
      
    // Return sum of array
    return lis.reduce((a, b) => a + b, 0);
}
  
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
  
console.log(sumOfElements(arr, n));


Output

21

Time Complexity: O(n)
Auxiliary Space: O(n)



Last Updated : 13 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads