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.


Input : arr[] = {1, 1, 2, 2, 3, 3, 3}
Output : 6
The even occurring element is 1 and 2, and it's number
of occurrence is 2. 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.


  • 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:





// CPP 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++) {
    // variable to stroe sum of all
    // even occurring elements
    int sum = 0;
    // loop to iteratre 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;




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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.