Sum of all even occurring element in an array
Last Updated :
11 Jul, 2025
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>
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);
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));
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem