Sum of distinct elements when elements are in range 1 to n
Last Updated :
24 Mar, 2023
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, 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 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.
Implementation:
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.
Python3
# 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
?>
JavaScript
<script>
// java script 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)
{
let sum = 0;
for (let 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
let a = [5, 1, 2, 4, 6, 7, 3, 6, 7];
let n = a.length;
document.write( sumOfDistinct(a, n));
//contributed by bobby
</script>
Time complexity: O(n)
Auxiliary Space : O(1)
Similar Reads
Find sum of non-repeating (distinct) elements in an array 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 : 78Here we take 12, 10, 9, 45, 2 for sumbecause it's distinct elements Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4}
14 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
Count Distinct Elements In Every Window of Size K Given an array arr[] of size n and an integer k, return the count of distinct numbers in all windows of size k. Examples: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4Output: [3, 4, 4, 3]Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3. Second window is [2, 1, 3, 4] count of d
10 min read
Queries for number of distinct elements in a subarray | Set 2 Given an array arr[] of N integers and Q queries. Each query can be represented by two integers L and R. The task is to find the count of distinct integers in the subarray arr[L] to arr[R].Examples: Input: arr[] = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9 }, L = 0, R = 4 Output: 3Input: arr[] = { 1, 1, 2, 1, 3
12 min read
Queries for number of distinct elements in a subarray | Set 2 Given an array arr[] of N integers and Q queries. Each query can be represented by two integers L and R. The task is to find the count of distinct integers in the subarray arr[L] to arr[R].Examples: Input: arr[] = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9 }, L = 0, R = 4 Output: 3Input: arr[] = { 1, 1, 2, 1, 3
12 min read
Count number of distinct pairs whose sum exists in the given array Given an array of N positive integers. Count the number of pairs whose sum exists in the given array. While repeating pairs will not be counted again. And we can't make a pair using same position element. Eg : (2, 1) and (1, 2) will be considered as only one pair. Please read all examples carefully.
7 min read