Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Sum of all even frequency elements in Matrix
Next article icon

Sum of all odd frequency elements in an array

Last Updated : 27 Mar, 2023
Comments
Improve
Suggest changes
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)


Next Article
Sum of all even frequency elements in Matrix

B

barykrg
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • cpp-unordered_map
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • 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 : 6The even occurring element are
    12 min read
  • Sum of all odd frequency elements in a Matrix
    Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all odd occurring elements in the given matrix. That is the sum of all such elements whose frequency is odd in the matrix. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 5, 3}} Output : 18 The odd occu
    5 min read
  • Delete all odd frequency elements from an Array
    Given an array arr containing integers of size N, the task is to delete all the elements from the array that have odd frequencies.Examples: Input: arr[] = {3, 3, 3, 2, 2, 4, 7, 7} Output: {2, 2, 7, 7} Explanation: Frequency of 3 = 3 Frequency of 2 = 2 Frequency of 4 = 1 Frequency of 7 = 2 Therefore,
    5 min read
  • Sum of all even frequency elements in Matrix
    Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all even occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 5, 3}} Output : 18 The even o
    5 min read
  • Program to print Sum of even and odd elements in an array
    Prerequisite - Array Basics Given an array, write a program to find the sum of values of even and odd index positions separately. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6} Output :Even index positions sum 9 Odd index positions sum 12 Explanation: Here, n = 6 so there will be 3 even index position
    13 min read
  • Difference between sum of odd and even frequent elements in an Array
    Given an array arr[] of integers, the task is to find the absolute difference between the sum of all odd frequent array elements and the sum of all even frequent array elements. Examples: Input: arr[] = {1, 5, 5, 2, 4, 3, 3} Output: 9 Explanation: The even frequent elements are 5 and 3 (both occurri
    12 min read
  • Sum of all minimum frequency elements in Matrix
    Given a NxM matrix of integers containing duplicate elements. The task is to find the sum of all minimum occurring elements in the given matrix. That is the sum of all such elements whose frequency is even in the matrix. Examples: Input : mat[] = {{1, 1, 2}, {2, 3, 3}, {4, 5, 3}} Output : 9 The min
    6 min read
  • Count of odd and even sum pairs in an array
    Given an array arr[] of N positive integers, the task is to find the number of pairs with odd sum and the number of pairs with even sum.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: Odd pairs = 6 Even pairs = 4Input: arr[] = {7, 4, 3, 2} Output: Odd pairs = 4 Even pairs = 2 Naive Approach: The na
    8 min read
  • Sum of elements from an array having even parity
    Given an array arr[], the task is to calculate the sum of the elements from the given array which has even parity i.e. the number of set bits is even using bitwise operator. Examples: Input: arr[] = {2, 4, 3, 5, 9} Output: 17 Only 3(0011), 5(0101) and 9(1001) have even parity So 3 + 5 + 9 = 17 Input
    6 min read
  • Count number of even and odd length elements in an Array
    Given an array arr[] of integers of size N, the task is to find the number elements of the array having even and odd length.Examples: Input: arr[] = {14, 735, 3333, 223222} Output: Number of even length elements = 3 Number of odd length elements = 1 Input: arr[] = {1121, 322, 32, 14783, 44} Output:
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences