Skip to main content

Sum of unique elements in array

Given an array of integer elements. Which may contain duplicate elements. Our goal is to find the sum of all elements that are not repeated in the array.

Example 1
 ---------
 arr = [4,1,2,3,4]
 sum =  1 + 2 + 3
     = 6
Example 2
---------
 arr = [1,2,-3,1]
 sum =  2 + -3
     = -1
Example 3
---------
 arr = [1,2]
 sum =  1 + 2
     = 3
 

Here given code implementation process.

// C++ Program 
// Sum of unique elements in array
#include <iostream>
#include <map>

using namespace std;

// Show the elements of given array
void display(int arr[], int size)
{
    cout << " \n Array element : ";
    // Display array elements values
    for (int i = 0; i < size; ++i)
    {
        cout << " " << arr[i];
    }
    cout << endl;
}
// This method are accept an array of integers and find the sum of distinct element
void unique_sum(int arr[], int size)
{
    // Define a map of (key integer and value integers)
    map < int, int > mp;
    // Create a iterator of map which is traverse map elements
    map < int, int > ::iterator element;
    // Create a variable which is collect the sum of  all unique values
    long long result = 0;
    bool work = false;
    // iterate the loop through by size
    for (int i = 0; i < size; ++i)
    {
        // In this given below statements are work in two cases
        // Case 1 : When map contains given element. In this case 
        //          it will incrementing element value (occurrence by one value) 
        // Case 2 : When elements are not exist in map. In this situation it will 
        //          add new element into map and set its occurrence as one 
        mp[arr[i]]++;
    }
    // For confirmation of working element
    display(arr, size);
    cout << " [";
    // iterating map element
    for (element = mp.begin(); element != mp.end(); ++element)
    {
        if (element->second == 1)
        {
            work = true;
            cout << " " << element->first;
            // When elements are exist at only once
            result += element->first;
        }
    }
    cout << " ]" << endl;
    if (work == true)
    {
        // Display result
        cout << " Sum : " << result << endl;
    }
    else
    {
        // When no result
        cout << " Sum : None  " << endl;
    }
}
int main()
{
    // Define the array of integer elements
    int arr1[] = {
        1 , 2 , 5 , 2 , -2 , 1
    };
    // Second array
    int arr2[] = {
        1 , 5 , 6 , 1 , 4 , 6 , 2
    };
    // Third array
    int arr3[] = {
        1 , 1 , 1
    };
    // Get the size of arr1
    int size = sizeof(arr1) / sizeof(arr1[0]);
    // 5 + (-2) 
    unique_sum(arr1, size); 
    // Get the size of arr2
    size = sizeof(arr2) / sizeof(arr2[0]);
    // 5 + 4 + 2
    unique_sum(arr2, size); 
    // Get the size of arr3
    size = sizeof(arr3) / sizeof(arr3[0]);
    // None
    unique_sum(arr3, size); 
    return 0;
}

Output

 Array element :  1 2 5 2 -2 1
 [ -2 5 ]
 Sum : 3

 Array element :  1 5 6 1 4 6 2
 [ 2 4 5 ]
 Sum : 11

 Array element :  1 1 1
 [ ]
 Sum : None
/*
   Java program
   Sum of unique elements in array
*/
import java.util.HashMap;
import java.util.Map;

public class Detection
{
    // This function are displaying given array elements
    public void display(int[] arr, int size)
    {
        System.out.print(" Array : ");
        for (int i = 0; i < size; ++i)
        {
            System.out.print("  " + arr[i]);
        }
        System.out.print("\n");
}
// This method are accept an array of integers and find the sum of distinct element
public void uniqueSum(int[] arr, int n)
{
    // Define a map of (key integer and value integers)
    Map < Integer, Integer > map = new HashMap < > ();
    // Create a variable which is collect the sum of  all unique values
    long result = 0;
    // resultatant indicator
    boolean work = false;
    // iterate the loop through by array size
    for (int i = 0; i < n; ++i)
    {
        if (map.containsKey(arr[i]))
        {
            //when key exist then put new key
            map.put(arr[i], map.get(arr[i]) + 1);
        }
        else
        {
            map.put(arr[i], 1);
        }
    }
    // For confirmation of working element
    this.display(arr, n);
    System.out.print(" [");
    // iterating map element
    for (int key: map.keySet())
    {
        if (map.get(key) == 1)
        {
            work = true;
            System.out.print(" " + key);
            result += key;
        }
    }
    System.out.print(" ]\n");
    if (work == true)
    {
        //Display result
        System.out.print(" Sum : " + result + "\n");
    }
    else
    {
        //When no result
        System.out.print(" Sum : None\n");
    }
}
public static void main(String[] args)
{
    Detection task = new Detection();
    // Define the array of integer elements
    int[] arr1 = {
        1 , 2 , 5 , 2 , -2 , 1
    };
    // Second array
    int[] arr2 = {
        1 , 5 , 6 , 1 , 4 , 6 , 2
    };
    // Third array
    int[] arr3 = {
        1 , 1 , 1
    };
    // Get the size of arr1
    int size = arr1.length;
    // 5 + (-2) 
    task.uniqueSum(arr1, size);
    // Get the size of arr2
    size = arr2.length;
    // 5 + 4 + 2
    task.uniqueSum(arr2, size);
    // Get the size of arr3
    size = arr3.length;
    task.uniqueSum(arr3, size);
}
}

Output

 Array :   1  2  5  2  -2  1
 [ -2 5 ]
 Sum : 3
 Array :   1  5  6  1  4  6  2
 [ 2 4 5 ]
 Sum : 11
 Array :   1  1  1
 [ ]
 Sum : None
/*
   C# program
   Sum of unique elements in array
*/
// Include namespace system
using System;
using System.Collections.Generic;
public class Detection
{
    // This function are displaying given array elements
    public void display(int[] arr, int size)
    {
        Console.Write(" Array : ");
        for (int i = 0; i < size; ++i)
        {
            Console.Write("  " + arr[i]);
        }
        Console.Write("\n");
    }
    // This method are accept an array of integers and find the sum of distinct element
    public void uniqueSum(int[] arr, int n)
    {
        // Define a dictionary of (key integer and value integers)
        Dictionary < int, int > map = new Dictionary < int, int > ();
        // Create a variable which is collect the sum of  all unique values
        long result = 0;
        // resultatant indicator
        Boolean work = false;
        // iterate the loop through by array size
        for (int i = 0; i < n; ++i)
        {
            if (map.ContainsKey(arr[i]))
            {
                map[arr[i]] += 1;
            }
            else
            {
                map.Add(arr[i], 1);
            }
        }
        // For confirmation of working element
        this.display(arr, n);
        Console.Write(" [");
        // iterating dictionary element
        foreach(KeyValuePair < int, int > entry in map)
        {
            if (entry.Value == 1)
            {
                // When result are exist
                work = true;
                Console.Write(" " + entry.Key);
                result += entry.Key;
            }
        }
        Console.Write(" ]\n");
        if (work == true)
        {
            // Display result
            Console.Write(" Sum : " + result + "\n");
        }
        else
        {
            // When no result
            Console.Write(" Sum : None\n");
        }
    }
    public static void Main(String[] args)
    {
        Detection task = new Detection();
        // Define the array of integer elements
        int[] arr1 = {
            1 , 2 , 5 , 2 , -2 , 1
        };
        // Second array
        int[] arr2 = {
            1 , 5 , 6 , 1 , 4 , 6 , 2
        };
        // Third array
        int[] arr3 = {
            1 , 1 , 1
        };
        // Get the size of arr1
        int size = arr1.Length;
        // 5 + (-2)
        task.uniqueSum(arr1, size);
        // Get the size of arr2
        size = arr2.Length;
        // 5 + 4 + 2
        task.uniqueSum(arr2, size);
        // Get the size of arr3
        size = arr3.Length;
        task.uniqueSum(arr3, size);
    }
}

Output

 Array :   1  2  5  2  -2  1
 [ 5 -2 ]
 Sum : 3
 Array :   1  5  6  1  4  6  2
 [ 5 4 2 ]
 Sum : 11
 Array :   1  1  1
 [ ]
 Sum : None
<?php
/*
   Php program
   Sum of unique elements in array
*/
class Detection
{
    // This function are displaying given array elements
    public  function display($arr, $size)
    {
        echo " Array : ";
        for ($i = 0; $i < $size; ++$i)
        {
            echo "  ". $arr[$i];
        }
        echo "\n";
    }
    // This method are accept an array of integers and find the sum of distinct element
    public  function uniqueSum( $arr, $n)
    {
        // Define a array 
        $map = [];
        // Create a variable which is collect the sum of  all unique values
        $result = 0;
        // resultatant indicator
        $work = false;
        // iterate the loop through by array size
        for ($i = 0; $i < $n; ++$i)
        {
            if (array_key_exists($arr[$i], $map))
            { //when key exist then put new key
                $map[$arr[$i]] = $map[$arr[$i]] + 1;
            }
            else
            {
                $map[$arr[$i]] = 1;
            }
        }
        // For confirmation of working element
        $this->display($arr, $n);
        echo " [";
        // iterating map element
        foreach($map as $key => $value)
        {
            if ($value == 1)
            {
                $work = true;
                echo " ". $key;
                $result += $key;
            }
        }
        echo " ]\n";
        if ($work == true)
        {
            //Display result
            echo " Sum : ". $result ."\n\n";
        }
        else
        {
            //When no result
            echo " Sum : None\n\n";
        }
    }
}

function main()
{
    $task = new Detection();
    // Define the array of integer elements
    $arr1 = array(1, 2, 5, 2, -2, 1);
    // Second array
    $arr2 = array(1, 5, 6, 1, 4, 6, 2);
    // Third array
    $arr3 = array(1, 1, 1);
    // Get the size of arr1
    $size = count($arr1);
    // 5 + (-2)
    $task->uniqueSum($arr1, $size);
    // Get the size of arr2
    $size = count($arr2);
    // 5 + 4 + 2
    $task->uniqueSum($arr2, $size);
    // Get the size of arr3
    $size = count($arr3);
    $task->uniqueSum($arr3, $size);
}
main();

Output

 Array :   1  2  5  2  -2  1
 [ 5 -2 ]
 Sum : 3

 Array :   1  5  6  1  4  6  2
 [ 5 4 2 ]
 Sum : 11

 Array :   1  1  1
 [ ]
 Sum : None
/*
   Node Js program
   Sum of unique elements in array
*/
class Detection
{
    // This function are displaying given array elements
    display(arr, size)
    {
        process.stdout.write(" Array : ");
        for (var i = 0; i < size; ++i)
        {
            process.stdout.write("  " + arr[i]);
        }
        process.stdout.write("\n");
    }
    // This method are accept an array of integers and find the sum of distinct element
    uniqueSum(arr, n)
    {
        // Define a map 
         let map = new Map();
        // Create a variable which is collect the sum of  all unique values
        var result = 0;
        // resultatant indicator
        var work = false;
        // iterate the loop through by array size
        for (var i = 0; i < n; ++i)
        {
            if (map.has(arr[i]))
            {
                map.set(arr[i], map.get(arr[i]) + 1);
            }
            else
            {
                map.set(arr[i], 1);
            }
        }
        // For confirmation of working element
        this.display(arr, n);
        process.stdout.write(" [");
        // iterating map element
        for(let [key,value] of map.entries())
        {
            if (value == 1)
            {
                work = true;
                process.stdout.write(" " + key);
                result += key;
            }
        }
        process.stdout.write(" ]\n");
        if (work == true)
        {
            //Display result
            console.log(" Sum : " + result + "\n");
        }
        else
        {
            //When no result
            console.log(" Sum : None\n");
        }
    }
}

function main()
{
    var task = new Detection();
    // Define the array of integer elements
    var arr1 = [1, 2, 5, 2, -2, 1];
    // Second array
    var arr2 = [1, 5, 6, 1, 4, 6, 2];
    // Third array
    var arr3 = [1, 1, 1];
    // Get the size of arr1
    var size = arr1.length;
    // 5 + (-2)
    task.uniqueSum(arr1, size);
    // Get the size of arr2
    size = arr2.length;
    // 5 + 4 + 2
    task.uniqueSum(arr2, size);
    // Get the size of arr3
    size = arr3.length;
    task.uniqueSum(arr3, size);
}
main();

Output

 Array :   1  2  5  2  -2  1
 [ 5 -2 ]
 Sum : 3

 Array :   1  5  6  1  4  6  2
 [ 5 4 2 ]
 Sum : 11

 Array :   1  1  1
 [ ]
 Sum : None
# 
#    Python 3 program
#    Sum of unique elements in array

class Detection :
    #  This function are displaying given list elements
    def display(self, arr, size) :
        print(" Array : ", end = "")
        i = 0
        while (i < size) :
            print("  ", arr[i], end = "")
            i += 1
        
        print(end = "\n")
    
    #  This method are accept an list of integers and find the sum of distinct element
    def uniqueSum(self, arr, n) :
        #  Define a dict
        map = dict()
        #  Create a variable which is collect the sum of  all unique values
        result = 0
        #  resultatant indicator
        work = False
        #  iterate the loop through by list size
        i = 0
        while (i < n) :
            if (arr[i] in map.keys()) :
                # when key exist then put new key
                map[arr[i]] = map.get(arr[i]) + 1
            else :
                map[arr[i]] = 1
            
            i += 1
        
        #  For confirmation of working element
        self.display(arr, n)
        print(" [", end = "")
        #  iterating map element
        for key, value in map.items() :
            if (value == 1) :
                work = True
                print(" ", key, end = "")
                result += key
            
        
        print(" ]")
        if (work == True) :
            # Display result
            print(" Sum : ", result )
        else :
            # When no result
            print(" Sum : None")
        
    

def main() :
    task = Detection()
    #  Define the list of integer elements
    arr1 = [1, 2, 5, 2, -2, 1]
    #  Second list
    arr2 = [1, 5, 6, 1, 4, 6, 2]
    #  Third list
    arr3 = [1, 1, 1]
    #  Get the size of arr1
    size = len(arr1)
    #  5 + (-2)
    task.uniqueSum(arr1, size)
    #  Get the size of arr2
    size = len(arr2)
    #  5 + 4 + 2
    task.uniqueSum(arr2, size)
    #  Get the size of arr3
    size = len(arr3)
    task.uniqueSum(arr3, size)

if __name__ == "__main__": main()

Output

 Array :    1   2   5   2   -2   1
 [  5  -2 ]
 Sum :  3
 Array :    1   5   6   1   4   6   2
 [  2  4  5 ]
 Sum :  11
 Array :    1   1   1
 [ ]
 Sum : None
#    Ruby program
#    Sum of unique elements in array

class Detection 
    #  This function are displaying given array elements
    def display(arr, size) 
        print(" Array : ")
        i = 0
        while (i < size) 
            print("  ", arr[i])
            i += 1
        end

        print("\n")
    end

    #  This method are accept an array of integers and find the sum of distinct element
    def uniqueSum(arr, n) 
        #  Define a hash 
        map = Hash.new 
        #  Create a variable which is collect the sum of  all unique values
        result = 0
        #  resultatant indicator
        work = false
        #  iterate the loop through by array size
        i = 0
        while (i < n) 
            if (map.key?(arr[i])) 
                map[arr[i]] = map[arr[i]] + 1
            else 
                map[arr[i]] = 1
            end

            i += 1
        end

        #  For confirmation of working element
        self.display(arr, n)
        print(" [")
        #  iterating map element
        map.each { |key,value|
            if (value == 1) 
                work = true
                print(" ", key)
                result += key
            end
        }
        print(" ]\n")
        if (work == true) 
            # Display result
            print(" Sum : ", result ,"\n")
        else 
            # When no result
            print(" Sum : None\n")
        end

    end

end

def main() 
    task = Detection.new()
    #  Define the array of integer elements
    arr1 = [1, 2, 5, 2, -2, 1]
    #  Second array
    arr2 = [1, 5, 6, 1, 4, 6, 2]
    #  Third array
    arr3 = [1, 1, 1]
    #  Get the size of arr1
    size = arr1.length
    #  5 + (-2)
    task.uniqueSum(arr1, size)
    #  Get the size of arr2
    size = arr2.length
    #  5 + 4 + 2
    task.uniqueSum(arr2, size)
    #  Get the size of arr3
    size = arr3.length
    task.uniqueSum(arr3, size)
end

main()

Output

 Array :   1  2  5  2  -2  1
 [ 5 -2 ]
 Sum : 3
 Array :   1  5  6  1  4  6  2
 [ 5 4 2 ]
 Sum : 11
 Array :   1  1  1
 [ ]
 Sum : None
import scala.collection.mutable.Map;
/*
   Scala program
   Sum of unique elements in array
*/
class Detection
{
    // This function are displaying given array elements
    def display(arr: Array[Int], size: Int): Unit = {
        print(" Array : ");
        var i: Int = 0;
        while (i < size)
        {
            print("  " + arr(i));
            i += 1;
        }
        print("\n");
    }
    // This method are accept an array of integers and find the sum of distinct element
    def uniqueSum(arr: Array[Int], n: Int): Unit = {
        // Define a map of (key integer and value integers)
        var map: Map[Int, Int] = Map.empty[Int, Int];
        // Create a variable which is collect the sum of  all unique values
        var result: Long = 0;
        // resultatant indicator
        var work: Boolean = false;
        // iterate the loop through by array size
        var i: Int = 0;
        while (i < n)
        {
            if (map.contains(arr(i)))
            {
                map(arr(i)) = map.get(arr(i)).get + 1;
            }
            else
            {
                map(arr(i)) = 1;
            }
            i += 1;
        }
        // For confirmation of working element
        this.display(arr, n);
        print(" [");
        // iterating map element
        map.keys.foreach{ key => 
            if (map.get(key).get == 1)
            {
                work = true;
                print(" " + key);
                result += key;
            }
        }
        print(" ]\n");
        if (work == true)
        {
            //Display result
            print(" Sum : " + result + "\n");
        }
        else
        {
            //When no result
            print(" Sum : None\n");
        }
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var task: Detection = new Detection();
        // Define the array of integer elements
        var arr1: Array[Int] = Array(1, 2, 5, 2, -2, 1);
        // Second array
        var arr2: Array[Int] = Array(1, 5, 6, 1, 4, 6, 2);
        // Third array
        var arr3: Array[Int] = Array(1, 1, 1);
        // Get the size of arr1
        var size: Int = arr1.length;
        // 5 + (-2)
        task.uniqueSum(arr1, size);
        // Get the size of arr2
        size = arr2.length;
        // 5 + 4 + 2
        task.uniqueSum(arr2, size);
        // Get the size of arr3
        size = arr3.length;
        task.uniqueSum(arr3, size);
    }
}

Output

 Array :   1  2  5  2  -2  1
 [ -2 5 ]
 Sum : 3
 Array :   1  5  6  1  4  6  2
 [ 2 4 5 ]
 Sum : 11
 Array :   1  1  1
 [ ]
 Sum : None
/*
   Swift 4 program
   Sum of unique elements in array
*/
class Detection
{
    // This function are displaying given array elements
    func display(_ arr: [Int], _ size: Int)
    {
        print(" Array : ", terminator: "");
        var i: Int = 0;
        while (i < size)
        {
            print("  ", arr[i], terminator: "");
            i += 1;
        }
        print(terminator: "\n");
    }
    // This method are accept an array of integers and find the sum of distinct element
    func uniqueSum(_ arr: [Int], _ n: Int)
    {
        // Define a dictionary of (key integer and value integers)
        var map = [Int: Int]();
        // Create a variable which is collect the sum of  all unique values
        var result: Int = 0;
        // resultatant indicator
        var work: Bool = false;
        // iterate the loop through by array size
        var i: Int = 0;
        while (i < n)
        {
            if (map.keys.contains(arr[i]))
            {
                //when key exist then put new key
                map[arr[i]] = map[arr[i]]! + 1;
            }
            else
            {
                map[arr[i]] = 1;
            }
            i += 1;
        }
        // For confirmation of working element
        self.display(arr, n);
        print(" [", terminator: "");
        // iterating map element
        for (key, value) in map
        {
            if (value == 1)
            {
                work = true;
                print(" ", key, terminator: "");
                result += key;
            }
        }
        print(" ]");
        if (work == true)
        {
            //Display result
            print(" Sum : ", result );
        }
        else
        {
            //When no result
            print(" Sum : None");
        }
    }
}
func main()
{
    let task: Detection = Detection();
    // Define the array of integer elements
    let arr1: [Int] = [1, 2, 5, 2, -2, 1];
    // Second array
    let arr2: [Int] = [1, 5, 6, 1, 4, 6, 2];
    // Third array
    let arr3: [Int] = [1, 1, 1];
    // Get the size of arr1
    var size: Int = arr1.count;
    // 5 + (-2)
    task.uniqueSum(arr1, size);
    // Get the size of arr2
    size = arr2.count;
    // 5 + 4 + 2
    task.uniqueSum(arr2, size);
    // Get the size of arr3
    size = arr3.count;
    task.uniqueSum(arr3, size);
}
main();

Output

 Array :    1   2   5   2   -2   1
 [  5  -2 ]
 Sum :  3
 Array :    1   5   6   1   4   6   2
 [  5  2  4 ]
 Sum :  11
 Array :    1   1   1
 [ ]
 Sum : None
/*
   Kotlin program
   Sum of unique elements in array
*/
class Detection
{
    // This function are displaying given array elements
    fun display(arr: Array < Int > , size: Int): Unit
    {
        print(" Array : ");
        var i: Int = 0;
        while (i < size)
        {
            print("  " + arr[i]);
            i += 1;
        }
        print("\n");
    }
    // This method are accept an array of integers and find the sum of distinct element
    fun uniqueSum(arr: Array < Int > , n: Int): Unit
    {
        // Define a map of (key integer and value integers)
        var map = mutableMapOf<Int, Int>();
        // Create a variable which is collect the sum of  all unique values
        var result: Long = 0;
        // resultatant indicator
        var work: Boolean = false;
        // iterate the loop through by array size
        var i: Int = 0;
        while (i < n)
        {
            if (map.containsKey(arr[i]))
            {
                map.put(arr[i], map.getValue(arr[i]) + 1);
            }
            else
            {
                map.put(arr[i], 1);
            }
            i += 1;
        }
        // For confirmation of working element
        this.display(arr, n);
        print(" [");
        // iterating map element
        for( (key, value) in map )
        {
            if (value == 1)
            {
                work = true;
                print(" " + key);
                result += key;
            }
        }
        print(" ]\n");
        if (work == true)
        {
            //Display result
            print(" Sum : " + result + "\n");
        }
        else
        {
            //When no result
            print(" Sum : None\n");
        }
    }
}
fun main(args: Array <String> ): Unit
{
    var task: Detection = Detection();
    // Define the array of integer elements
    var arr1: Array < Int > = arrayOf(1, 2, 5, 2, -2, 1);
    // Second array
    var arr2: Array < Int > = arrayOf(1, 5, 6, 1, 4, 6, 2);
    // Third array
    var arr3: Array < Int > = arrayOf(1, 1, 1);
    // Get the size of arr1
    var size: Int = arr1.count();
    // 5 + (-2)
    task.uniqueSum(arr1, size);
    // Get the size of arr2
    size = arr2.count();
    // 5 + 4 + 2
    task.uniqueSum(arr2, size);
    // Get the size of arr3
    size = arr3.count();
    task.uniqueSum(arr3, size);
}

Output

 Array :   1  2  5  2  -2  1
 [ 5 -2 ]
 Sum : 3
 Array :   1  5  6  1  4  6  2
 [ 5 4 2 ]
 Sum : 11
 Array :   1  1  1
 [ ]
 Sum : None
Unique elements in array




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment