Given an array of n elements such that every element of 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, 1}
Output: 1
The problem has appeared here as a general problem and the solution will work for the above case also. But a better approach is explained below.
The approach is to mark the occurrences of the array elements by making the elements at those indices as negative. Example, a[0] = 1, a[1] = 1, a[2] = 1.
We check if a[abs(a[i])-1] is >=0, if yes, mark a[abs(a[i])-1] as negative. i.e. a[0] = 1 >=0, we mark a[1-1] as a[0] = -1. Next, a[1], check if (abs(a[1]-1) is +ve or not. If -ve, it means a[1] has already occurred before, else it is the first occurrence of this element. Refer the below code.
C++
// C++ program to find sum of distinct elements #include <iostream> using namespace std; // Returns sum of distinct elements in arr[] assuming // that elements in a[] are in range from 1 to n. int sumOfDistinct(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) { // If element appears first time if (a[abs(a[i]) - 1] >= 0) { sum += abs(a[i]); a[abs(a[i]) - 1] *= -1; } } return sum; } // Driver code int main() { int a[] = { 5, 1, 2, 4, 6, 7, 3, 6, 7 }; int n = sizeof(a)/sizeof(a[0]); cout << sumOfDistinct(a, n) << endl; return 0; } |
Java
// JAVA program to find sum of distinct // elements in sorted order import java.io.*; import java.util.*; import java.math.*; class GFG{ // Returns sum of distinct elements in arr[] // assuming that elements in a[] are in // range from 1 to n. static int sumOfDistinct(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) { // If element appears first time if (a[Math.abs(a[i]) - 1] >= 0) { sum += Math.abs(a[i]); a[Math.abs(a[i]) - 1] *= -1; } } return sum; } // Driver code public static void main(String args[]) { int a[] = { 5, 1, 2, 4, 6, 7, 3, 6, 7 }; int n = a.length; System.out.println(sumOfDistinct(a, n) ); } } // This code is contributed by Nikita Tiwari. |
Python
# Python program to find sum of distinct elements # in sorted order import math # Returns sum of distinct elements in arr[] # assuming that elements in a[] are in # range from 1 to n. def sumOfDistinct(a , n) : sum = 0 i = 0 while i < n: # If element appears first time if (a[abs(a[i]) - 1] >= 0) : sum = sum + abs(a[i]) a[abs(a[i]) - 1] = a[abs(a[i]) - 1] * (-1) i = i + 1 return sum; # Driver code a = [ 5, 1, 2, 4, 6, 7, 3, 6, 7 ] n = len(a) print sumOfDistinct(a, n) # This code is contributed by Nikita Tiwari. |
C#
// C# program to find sum of distinct // elements in sorted order using System; class GFG{ // Returns sum of distinct elements // in arr[] assuming that elements // in a[] are in range from 1 to n static int sumOfDistinct(int []a, int n) { int sum = 0; for (int i = 0; i < n; i++) { // If element appears first time if (a[Math.Abs(a[i]) - 1] >= 0) { sum += Math.Abs(a[i]); a[Math.Abs(a[i]) - 1] *= - 1; } } return sum; } // Driver code public static void Main() { int []a = {5, 1, 2, 4, 6, 7, 3, 6, 7}; int n = a.Length; Console.Write(sumOfDistinct(a, n)); } } // This code is contributed by Nitin Mittal |
PHP
<?php // PHP program to find sum of // distinct elements // Returns sum of distinct // elements in arr[] assuming // that elements in a[] are // in range from 1 to n. function sumOfDistinct($a, $n) { $sum = 0; for ($i = 0; $i < $n; $i++) { // If element appears first time if ($a[abs($a[$i]) - 1] >= 0) { $sum += abs($a[$i]); $a[abs($a[$i]) - 1] *= -1; } } return $sum; } // Driver code $a = array(5, 1, 2, 4, 6, 7, 3, 6, 7); $n = sizeof($a); echo sumOfDistinct($a, $n) ; // This code is contributed by nitin mittal ?> |
Output:
28
Time complexity: O(n)
Auxiliary Space : O(1)
This article is contributed by Ekta Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Queries for elements having values within the range A to B in the given index range using Segment Tree
- Range Queries to count elements lying in a given Range : MO's Algorithm
- Find the count of distinct numbers in a range
- Count of distinct characters in a substring by given range for Q queries
- Count of distinct numbers in an Array in a range for Online Queries using Merge Sort Tree
- Construct sum-array with sum of elements in given range
- Sum of M maximum distinct digit sum from 1 to N that are factors of K
- Count numbers whose maximum sum of distinct digit-sum is less than or equals M
- Find sum of non-repeating (distinct) elements in an array
- Construct a distinct elements array with given size, sum and element upper bound
- Form an array of distinct elements with each element as sum of an element from each array
- Check if K distinct array elements form an odd sum
- Maximum distinct elements after removing k elements
- Length of array pair formed where one contains all distinct elements and other all same elements
- Split an array containing N elements into K sets of distinct elements
- Array range queries over range queries
- Range and Coefficient of range of Array
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Sum of elements of an AP in the given range
- Queries for the count of even digit sum elements in the given range using Segment Tree.
Improved By : nitin mittal

