Open In App

Sum of all odd frequency elements in an array

Last Updated : 27 Mar, 2023
Suggest changes
Share
Like Article
Like
Report

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

Examples: 

Input : arr[] = {1, 1, 2, 2, 3, 3, 3} Output : 9 The odd occurring element is 3, and it's number of occurrence is 3. Therefore sum of all 3's in the array = 9. Input : arr[] = {10, 20, 30, 40, 40} Output : 60 Elements with odd frequency are 10, 20 and 30. Sum = 60.

Approach:  

  • Traverse the array and use a 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 odd, if it is odd, then add this element to sum.

Below is the implementation of the above approach: 

C++
// CPP program to find the sum of all odd // occurring elements in an array #include <bits/stdc++.h> using namespace std; // Function to find the sum of all odd // occurring elements in an array int findSum(int arr[], int N) {  // Store frequencies 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  // odd occurring elements  int sum = 0;  // loop to iterate through map  for (auto itr = mp.begin(); itr != mp.end(); itr++) {  // check if frequency is odd  if (itr->second % 2 != 0)  sum += (itr->first) * (itr->second);  }  return sum; } // Driver Code int main() {  int arr[] = { 10, 20, 20, 10, 40, 40, 10 };  int N = sizeof(arr) / sizeof(arr[0]);  cout << findSum(arr, N);  return 0; } 
Java
// Java program to find the sum of all odd // occurring elements in an array import java.util.*; class GFG  { // Function to find the sum of all odd // occurring elements in an array static int findSum(int arr[], int N) {  // Store frequencies of elements  // of the array  Map<Integer,Integer> mp = new HashMap<>();  for (int i = 0; i < N; i++)  mp.put(arr[i],mp.get(arr[i])==null?1:mp.get(arr[i])+1);  // variable to store sum of all  // odd occurring elements  int sum = 0;  // loop to iterate through map  for (Map.Entry<Integer,Integer> entry : mp.entrySet())  {  // check if frequency is odd  if (entry.getValue() % 2 != 0)  sum += (entry.getKey()) * (entry.getValue());  }  return sum; } // Driver Code public static void main(String args[])  {  int arr[] = { 10, 20, 20, 10, 40, 40, 10 };  int N = arr.length;  System.out.println(findSum(arr, N)); } } /* This code is contributed by PrinciRaj1992 */ 
Python3
# Function to find sum of all odd  # occurring elements in an array import collections def findsum(arr, N): # Store frequencies of elements # of an array in dictionary mp = collections.defaultdict(int) for i in range(N): mp[arr[i]] += 1 # Variable to store sum of all  # odd occurring elements sum = 0 # loop to iterate through dictionary for i in mp: # Check if frequency is odd if (mp[i] % 2 != 0): sum += (i * mp[i]) return sum # Driver Code arr = [ 10, 20, 20, 10, 40, 40, 10 ] N = len(arr) print (findsum(arr, N)) # This code is contributed # by HardeepSingh.  
C#
// C# program to find the sum of all odd  // occurring elements in an array using System; using System.Collections.Generic; class GFG {  // Function to find the sum of all odd   // occurring elements in an array   public static int findSum(int[] arr, int N)  {  // Store frequencies of elements   // of the array   Dictionary<int,   int> mp = new Dictionary<int,   int>();  for (int i = 0; i < N; i++)  {  if (mp.ContainsKey(arr[i]))  mp[arr[i]]++;  else  mp.Add(arr[i], 1);  }  // variable to store sum of all   // odd occurring elements   int sum = 0;  // loop to iterate through map   foreach (KeyValuePair<int,   int> entry in mp)  {  // check if frequency is odd   if (entry.Value % 2 != 0)  sum += entry.Key * entry.Value;  }  return sum;  }  // Driver code   public static void Main(String[] args)  {  int[] arr = { 10, 20, 20, 10, 40, 40, 10 };  int n = arr.Length;  Console.WriteLine(findSum(arr, n));  } } // This code is contributed by // sanjeev2552 
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, 10, 40, 40, 10]; let N = arr.length document.write(findSum(arr, N)); // This code is contributed by gfgking. </script> 

Output
30

complexity Analysis:

  • 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 odd frequency multiplied by its frequency.

Below is the implementation:

C++
#include <iostream> #include <unordered_map> using namespace std; void sumOdd(int arr[], int n)  {  // Counting frequency of every element using unordered_map  unordered_map<int, int> freq;  for (int i = 0; i < n; i++) {  freq[arr[i]]++;  }  // Initializing sum to 0  int sum = 0;  // Traverse the frequency and sum all elements   // with odd frequency multiplied by its frequency  for (auto it : freq) {  if (it.second % 2 != 0) {  sum += it.first * it.second;  }  }  cout << sum << endl; } // Driver code int main() {  int arr[] = {10, 20, 30, 40, 40};  int n = sizeof(arr) / sizeof(arr[0]);  sumOdd(arr, n); } 
Python3
# Python3 implementation of the above approach from collections import Counter def sumOdd(arr, n): # Counting frequency of every  # element using Counter freq = Counter(arr) # Initializing sum 0 sum = 0 # Traverse the frequency and print all # sum all elements with odd 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, 30, 40, 40] n = len(arr) sumOdd(arr, n) # This code is contributed by vikkycirus 
C#
// C# implementation of the above approach using System; using System.Collections.Generic; using System.Linq; class MainClass {  // Function to return the sum of elements  // in an array having odd frequency  public static void sumOdd(int[] arr, int n)  {  // Dictionary is used to calculate frequency of  // elements of array  Dictionary<int, int> freq  = arr.GroupBy(x => x).ToDictionary(  x => x.Key, x => x.Count());  int sum = 0;  // Traverse the dictionary  foreach(KeyValuePair<int, int> entry in freq)  {  // Calculate the sum of elements  // having odd frequency  // multiplied by its frequency  if (entry.Value % 2 != 0) {  sum += entry.Key * entry.Value;  }  }  Console.WriteLine(sum);  }  // Driver code  public static void Main()  {  int[] arr = { 10, 20, 30, 40, 40 };  int n = arr.Length;  sumOdd(arr, n);  } } // This code is contributed by phasing17 
JavaScript
function sumOdd(arr, n) {  // Counting frequency of every  // element using Map  let freq = new Map();  for(let i=0; i<n; i++){  if(freq.has(arr[i])){  freq.set(arr[i], freq.get(arr[i])+1);  } else {  freq.set(arr[i], 1);  }  }  // Initializing sum to 0  let sum = 0;  // Traverse the frequency and sum all elements  // with odd frequency multiplied by its frequency  for(let [key, value] of freq){  if(value % 2 !== 0){  sum += key*value;  }  }  console.log(sum); } // Driver code let arr = [10, 20, 30, 40, 40]; let n = arr.length; sumOdd(arr, n); 
Java
/*package whatever //do not write package name here */ import java.util.HashMap; public class GFG {    static void sumOdd(int[] arr, int n) {    // Counting frequency of every element using HashMap  HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();  for (int i = 0; i < n; i++) {  if (freq.containsKey(arr[i])) {  freq.put(arr[i], freq.get(arr[i]) + 1);  } else {  freq.put(arr[i], 1);  }  }  // Initializing sum to 0  int sum = 0;  // Traverse the frequency and sum all elements   // with odd frequency multiplied by its frequency  for (HashMap.Entry<Integer, Integer> entry : freq.entrySet()) {  if (entry.getValue() % 2 != 0) {  sum += entry.getKey() * entry.getValue();  }  }  System.out.println(sum);  }    // Driver code  public static void main(String[] args) {  int[] arr = {10, 20, 30, 40, 40};  int n = arr.length;  sumOdd(arr, n);  } } 

Output
60

Complexity  Analysis:

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

Similar Reads

Practice Tags :