Find sum of non-repeating (distinct) elements in an array
Last Updated :
13 Sep, 2023
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
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>
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>
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));
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Product of non-repeating (distinct) elements in an Array
Given an integer array with duplicate elements. The task is to find the product of all distinct elements in the given array. Examples: Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10}; Output : 97200 Here we take 12, 10, 9, 45, 2 for product because these are the only distinct elements Input : arr
15 min read
k-th distinct (or non-repeating) element among unique elements in an array.
Given an integer array arr[], print kth distinct element in this array. The given array may contain duplicates and the output should print the k-th element among all unique elements. If k is more than the number of distinct elements, print -1.Examples:Input: arr[] = {1, 2, 1, 3, 4, 2}, k = 2Output:
7 min read
Find the only non-repeating element in a given array
Given an array A[] consisting of N (1 ? N ? 105) positive integers, the task is to find the only array element with a single occurrence. Note: It is guaranteed that only one such element exists in the array. Examples: Input: A[] = {1, 1, 2, 3, 3}Output: 2Explanation: Distinct array elements are {1,
10 min read
Sum of all elements repeating 'k' times in an array
Given an array, we have to find the sum of all the elements repeating k times in an array. We need to consider every repeating element just once in the sum. Examples: Input : arr[] = {2, 3, 9, 9} k = 1 Output : 5 2 + 3 = 5 Input : arr[] = {9, 8, 8, 8, 10, 4} k = 3 Output : 8 One simple solution is t
8 min read
Find the two repeating elements in a given array
Given an array arr[] of N+2 elements. All elements of the array are in the range of 1 to N. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. Examples:Input: arr = [4, 2, 4, 5, 2, 3, 1], N = 5Output: 4 2Explanation: The above array has n + 2 = 7 elemen
15+ min read
Find the first repeating element in an array of integers
Given an array of integers arr[], The task is to find the index of first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. Examples: Input: arr[] = {10, 5, 3, 4, 3, 5, 6}Output: 5 Explanation: 5 is the first element that repe
8 min read
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Print all Distinct (Unique) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once.Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2}Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4,
11 min read
Sum of distinct elements when elements are in range 1 to n
Given an array of n elements such that every element of the array is an integer in the range 1 to n, find the sum of all the distinct elements of the array. Examples: Input: arr[] = {5, 1, 2, 4, 6, 7, 3, 6, 7} Output: 28 The distinct elements in the array are 1, 2, 3, 4, 5, 6, 7 Input: arr[] = {1, 1
5 min read
Find the only repeating element in a sorted array of size n
Given a sorted array of n elements containing elements in range from 1 to n-1 i.e. one element occurs twice, the task is to find the repeating element in an array. Examples : Input : arr[] = { 1, 2 , 3 , 4 , 4}Output : 4Input : arr[] = { 1 , 1 , 2 , 3 , 4}Output : 1Brute Force: Traverse the input ar
8 min read