Sunday, November 17, 2024
Google search engine
HomeData Modelling & AISum of all even occurring element in an array

Sum of all even occurring element in an array

Given an array of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given array. That is the sum of all such elements whose frequency is even in the array.

Examples

Input : arr[] = {1, 1, 2, 2, 3, 3, 3}
Output : 6
The even occurring element are 1 and 2 (both occur two times).
Therefore sum of all 1's in the array = 1+1+2+2 = 6.
Input : arr[] = {10, 20, 30, 40, 40}
Output : 80
Element with even frequency are 40.
Sum = 40.

Approach

  • Traverse the array and use a unordered_map in C++ to store the frequency of elements of the array such that the key of map is the array element and value is its frequency in the array.
  • Then, traverse the map to find the frequency of elements and check if it is even, if it is even, then add this element to sum.

Below is the implementation of the above approach: 

C++




// C++ program to find the sum of all even
// occurring elements in an array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of all even
// occurring elements in an array
int findSum(int arr[], int N)
{
    // Map to store frequency of elements
    // of the array
    unordered_map<int, int> mp;
 
    for (int i = 0; i < N; i++) {
        mp[arr[i]]++;
    }
 
    // variable to store sum of all
    // even occurring elements
    int sum = 0;
 
    // loop to iterate through map
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {
 
        // check if frequency is even
        if (itr->second % 2 == 0)
            sum += (itr->first) * (itr->second);
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 20, 20, 40, 40 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << findSum(arr, N);
 
    return 0;
}


Java




// Java program to find the sum of all even
// occurring elements in an array
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
 
public class GFG {
    public static int element(int[] arr, int n)
    {
 
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; i++) {
            int count = 0;
            if (map.get(arr[i]) != null) {
                count = map.get(arr[i]);
            }
            map.put(arr[i], count + 1);
        }
 
        int sum = 0;
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() % 2 == 0) {
                sum += entry.getKey() * entry.getValue();
            }
        }
 
        return sum;
    }
 
    public static void main(String[] args)
    {
        int arr[] = { 1, 1, 2, 2, 3, 3, 3 };
 
        // sum should be = 1+1+2+2=6;
        int n = arr.length;
        System.out.println(element(arr, n));
    }
}


Python3




# Python3 program to find the sum
# of all even occurring elements
# in an array
 
# Function to find the sum of all even
# occurring elements in an array
def findSum(arr, N):
 
    # Map to store frequency of
    # elements of the array
    mp = {}
 
    for i in range(N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
 
    # Variable to store sum of all
    # even occurring elements
    Sum = 0
 
    # Loop to iterate through map
    for first, second in mp.items():
 
        # Check if frequency is even
        if (second % 2 == 0):
            Sum += (first) * (second)
 
    return Sum
     
# Driver code   
arr = [ 10, 20, 20, 40, 40 ]
 
N = len(arr)
 
print(findSum(arr, N))
 
# This code is contributed by divyeshrabadiya07


C#




// C# program to find the sum of all even
// occurring elements in an array
using System;
using System.Collections.Generic;
 
class GFG {
     
    static int element(int[] arr, int n)
    {
        Dictionary<int, int> map = new Dictionary<int, int>(); 
        for (int i = 0; i < n; i++)
        {
             
            if(!map.ContainsKey(arr[i]))
            {
                map.Add(arr[i], 1);
            }
            else
            {
                map[arr[i]] += 1;
            }
             
        }
  
        int sum = 0;
         
        foreach(KeyValuePair<int, int> entry in map)
        {
            if (entry.Value % 2 == 0)
            {
                sum += entry.Key * entry.Value;
            }
        }
  
        return sum;
    }
   
  // Driver code
  static void Main() {
        int[] arr = { 10, 20, 20, 40, 40};
  
        int n = arr.Length;
        Console.WriteLine(element(arr, n));
  }
}
 
// This code is contributed by divyesh072019


Javascript




<script>
// Javascript program to find the sum of all odd
// occurring elements in an array
 
// Function to find the sum of all odd
// occurring elements in an array
function findSum(arr, N)
{
 
    // Store frequencies of elements
    // of the array
    let mp = new Map();
    for (let i = 0; i < N; i++) {
        if (mp.has(arr[i])) {
            mp.set(arr[i], mp.get(arr[i]) + 1)
        } else {
            mp.set(arr[i], 1)
        }
    }
 
    // variable to store sum of all
    // odd occurring elements
    let sum = 0;
 
    // loop to iterate through map
    for (let itr of mp) {
 
        // check if frequency is odd
        if (itr[1] % 2 == 0)
            sum += (itr[0]) * (itr[1]);
    }
 
    return sum;
}
 
// Driver Code
 
let arr = [10, 20, 20, 40, 40];
 
let N = arr.length
 
document.write(findSum(arr, N));
 
// This code is contributed by _saurabh_jaiswal.
</script>


Output

120






Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(N)

Method 2: Using Built-in python functions:

  • Count the frequencies of every element using Counter function
  • Traverse the frequency dictionary and sum all the elements with occurrence even frequency multiplied by its frequency.

Below is the implementation:

C++




// C++ implementation
#include <iostream>
#include <unordered_map>
 
using namespace std;
 
void sumEven(int arr[], int n)
{
 
    // Counting frequency of every element
    unordered_map<int, int> freq;
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
 
    // initializing sum 0
    int sum = 0;
 
    // Traverse the freq and print all
    // sum all elements with even frequency
    // multiplied by its frequency
    for (auto it : freq) {
        if (it.second % 2 == 0) {
            sum = sum + it.first * it.second;
        }
    }
    cout << sum << endl;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 20, 40, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sumEven(arr, n);
 
    return 0;
}
 
// This code is contributed by vikkycirus.


Java




// Java program for the above approach
import java.util.*;
 
public class Main {
    public static void sumEven(int[] arr, int n)
    {
 
        // Counting frequency of every element
        Map<Integer, Integer> freq = new HashMap<>();
        for (int i = 0; i < n; i++) {
            freq.put(arr[i],
                     freq.getOrDefault(arr[i], 0) + 1);
        }
 
        // initializing sum 0
        int sum = 0;
 
        // Traverse the freq and print all
        // sum all elements with even frequency
        // multiplied by its frequency
        for (Map.Entry<Integer, Integer> entry :
             freq.entrySet()) {
            int key = entry.getKey();
            int value = entry.getValue();
            if (value % 2 == 0) {
                sum += key * value;
            }
        }
        System.out.println(sum);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 10, 20, 20, 40, 40 };
        int n = arr.length;
 
        sumEven(arr, n);
    }
}


Python3




# Python3 implementation
from collections import Counter
 
 
def sumEven(arr, n):
 
    # Counting frequency of every
    # element using Counter
    freq = Counter(arr)
     
    # initializing sum 0
    sum = 0
     
    # Traverse the freq and print all
    # sum all elements with even frequency
    # multiplied by its frequency
    for it in freq:
        if freq[it] % 2 == 0:
            sum = sum + it*freq[it]
    print(sum)
 
 
# Driver code
arr = [10, 20, 20, 40, 40]
n = len(arr)
 
sumEven(arr, n)
 
# This code is contributed by vikkycirus


C#




// C# implementation
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG {
    static void Main(string[] args)
    {
        int[] arr = { 10, 20, 20, 40, 40 };
        int n = arr.Length;
 
        sumEven(arr, n);
    }
 
    static void sumEven(int[] arr, int n)
    {
        // Counting frequency of every
        // element using Dictionary
        Dictionary<int, int> freq
            = arr.GroupBy(x = > x).ToDictionary(
                g = > g.Key, g = > g.Count());
 
        // initializing sum 0
        int sum = 0;
 
        // Traverse the freq and print all
        // sum all elements with even frequency
        // multiplied by its frequency
        foreach(KeyValuePair<int, int> pair in freq)
        {
            if (pair.Value % 2 == 0) {
                sum += pair.Key * pair.Value;
            }
        }
        Console.WriteLine(sum);
    }
}
 
// This code is contributed by phasing17


Javascript




function sumEven(arr)
{
 
    // Counting frequency of every element
    let freq = {};
    for (let i = 0; i < arr.length; i++) {
        if (freq[arr[i]] === undefined) {
            freq[arr[i]] = 1;
        } else {
            freq[arr[i]]++;
        }
    }
 
    // initializing sum 0
    let sum = 0;
 
    // Traverse the freq and print all
    // sum all elements with even frequency
    // multiplied by its frequency
    for (let key in freq) {
        if (freq[key] % 2 == 0) {
            sum = sum + key * freq[key];
        }
    }
    console.log(sum);
}
 
// Driver code
let arr = [10, 20, 20, 40, 40];
sumEven(arr);


Output

120







Time complexity: O(n) where n is size of given list “arr”
Auxiliary space: O(1)

Approach#3:using pointers

Algorithm

1. Sort the input array arr.
2. Initialize two pointers i and j to 0.
3. Initialize a variable sum to 0.
4.While j < len(arr):
a. If arr[j] is equal to arr[i], increment j.
b. Otherwise, if (j – i) % 2 == 0, add arr[i] * (j – i) to sum.
c. Set i to j.
5.If (j – i) % 2 == 0, add arr[i] * (j – i) to sum.
6. Return sum.

C++




#include <iostream>
#include <vector>
#include <algorithm> // Required for sorting
 
using namespace std;
 
// Function to calculate the sum of elements with even frequency
int sumEvenFreq(vector<int>& arr) {
    sort(arr.begin(), arr.end()); // Sort the array in ascending order
    int i = 0, j = 0;
    int sum = 0;
 
    // Loop to iterate through the array
    while (j < arr.size()) {
        if (arr[j] == arr[i]) {
            j++; // Increment j until the element changes
        } else {
            // If the frequency of elements between i and j is even
            if ((j - i) % 2 == 0) {
                sum += arr[i] * (j - i); // Add the element times its frequency to sum
            }
            i = j; // Move i to the new distinct element
        }
    }
 
    // Check if the last group of elements has even frequency
    if ((j - i) % 2 == 0) {
        sum += arr[i] * (j - i); // Add the element times its frequency to sum
    }
 
    return sum;
}
// Driver Code
int main() {
    vector<int> arr = {10, 20, 30, 40, 40};
    cout << "Sum of elements with even frequency: " << sumEvenFreq(arr) << endl;
    return 0;
}


Java




import java.util.Arrays;
 
public class Main {
    // Function to calculate the sum of elements with even frequency
    static int sumEvenFreq(int[] arr) {
        Arrays.sort(arr); // Sort the array in ascending order
        int i = 0, j = 0;
        int sum = 0;
 
        // Loop to iterate through the array
        while (j < arr.length) {
            if (arr[j] == arr[i]) {
                j++; // Increment j until the element changes
            } else {
                // If the frequency of elements between i and j is even
                if ((j - i) % 2 == 0) {
                    sum += arr[i] * (j - i); // Add the element times its frequency to sum
                }
                i = j; // Move i to the new distinct element
            }
        }
 
        // Check if the last group of elements has even frequency
        if ((j - i) % 2 == 0) {
            sum += arr[i] * (j - i); // Add the element times its frequency to sum
        }
 
        return sum;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 40};
        System.out.println("Sum of elements with even frequency: " + sumEvenFreq(arr));
    }
}


Python3




def sum_even_freq(arr):
    arr.sort()
    i = j = 0
    sum = 0
    while j < len(arr):
        if arr[j] == arr[i]:
            j += 1
        else:
            if (j - i) % 2 == 0:
                sum += arr[i] * (j - i)
            i = j
    if (j - i) % 2 == 0:
        sum += arr[i] * (j - i)
    return sum
arr = [ 10, 20, 30, 40, 40 ]
print(sum_even_freq(arr))


C#




using System;
using System.Collections.Generic;
using System.Linq; // Required for sorting
 
class Program
{
    // Function to calculate the sum of elements with even frequency
    static int SumEvenFreq(List<int> arr)
    {
        arr.Sort(); // Sort the list in ascending order
        int i = 0, j = 0;
        int sum = 0;
 
        // Loop to iterate through the list
        while (j < arr.Count)
        {
            if (arr[j] == arr[i])
            {
                j++; // Increment j until the element changes
            }
            else
            {
                // If the frequency of elements between i and j is even
                if ((j - i) % 2 == 0)
                {
                    sum += arr[i] * (j - i); // Add the element times its frequency to sum
                }
                i = j; // Move i to the new distinct element
            }
        }
 
        // Check if the last group of elements has even frequency
        if ((j - i) % 2 == 0)
        {
            sum += arr[i] * (j - i); // Add the element times its frequency to sum
        }
 
        return sum;
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 10, 20, 30, 40, 40 };
        Console.WriteLine("Sum of elements with even frequency: " + SumEvenFreq(arr));
    }
}


Javascript




function sum_even_freq(arr) {
    // Sort the array
    arr.sort();
    let i = 0;
    let j = 0;
    let sum = 0;
    while (j < arr.length) {
        if (arr[j] == arr[i]) {
            j += 1;
        } else {
            // If the frequency of the current element is even, add it to the sum
            if ((j - i) % 2 == 0) {
                sum += arr[i] * (j - i);
            }
            i = j;
        }
    }
    // Check the last element
    if ((j - i) % 2 == 0) {
        sum += arr[i] * (j - i);
    }
    return sum;
}
 
let arr = [10, 20, 30, 40, 40];
console.log(sum_even_freq(arr));


Output

80







Time complexity: O(n log n), where n is the length of the input array arr. The sort() function takes O(n log n) time in the worst case, and the while loop takes O(n) time to iterate through the sorted array. Therefore, the overall time complexity is dominated by the sort() function.
Space complexity: O(1), since we’re using a constant amount of extra space to store the pointers i and j, and the variable sum.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments