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:
Maximum difference between sum of even and odd indexed elements of a Subarray
Next article icon

Difference between sum of odd and even frequent elements in an Array

Last Updated : 08 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 occurring twice). 
Therefore, sum of all even frequent elements = 5 + 5 + 3 + 3 = 16. 
The odd frequent elements are 1, 2 and 4 (each occurring once). 
Therefore, sum of all odd frequent elements = 1 + 2 + 4 = 7. 
Difference between their sum = 16 – 7 = 9.

Input: arr[] = {1, 1, 2, 2, 3, 3} 
Output: 12 
Explanation: 
The even frequent array elements are 1, 2 and 3 (occurring twice). 
Therefore, sum of all even frequent elements = 12. 
Since there is no odd frequent element present in the array, difference = 12 – 0 = 12 
 

Approach: Follow the steps below to solve the problem: 

  • Initialize an unordered_map to store the frequency of array elements.
  • Traverse the array and update the frequency of array elements in the Map.
  • Then, traverse the map and add the elements having even frequency to a variable, say sum_even, and the ones with odd frequencies to another variable, say sum_odd.
  • Finally, print the difference between sum_odd and sum_even.

Below is the implementation of the above approach:

C++




// C++ program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of all even
// and odd frequent elements in an array
int findSum(int arr[], int N)
{
    // Stores the frequency of array elements
    unordered_map<int, int> mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update frequency of
        // current element
        mp[arr[i]]++;
    }
 
    // Stores sum of odd and even
    // frequent elements
    int sum_odd = 0, sum_even = 0;
 
    // Traverse the map
    for (auto itr = mp.begin();
        itr != mp.end(); itr++) {
 
        // If frequency is odd
        if (itr->second % 2 != 0)
 
            // Add sum of all occurrences of
            // current element to sum_odd
            sum_odd += (itr->first)
                    * (itr->second);
 
        // If frequency is even
        if (itr->second % 2 == 0)
 
            // Add sum of all occurrences of
            // current element to sum_even
            sum_even += (itr->first)
                        * (itr->second);
    }
 
    // Calculate difference
    // between their sum
    int diff = sum_even - sum_odd;
 
    // Return diff
    return diff;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 5, 5, 2, 4, 3, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findSum(arr, N);
 
    return 0;
}
 
 

Java




// Java program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
import java.util.*;
import java.io.*;
import java.math.*;
 
class GFG{
     
// Function to find the sum of all even
// and odd frequent elements in an array
static int findSum(int arr[], int N)
{
     
    // Stores the frequency of array elements
    Map<Integer,
        Integer> map = new HashMap<Integer,
                                   Integer>();
                                    
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of
        // current element
        if (!map.containsKey(arr[i]))
            map.put(arr[i], 1);
        else
            map.replace(arr[i], map.get(arr[i]) + 1);
    }
     
    // Stores sum of odd and even
    // frequent elements
    int sum_odd = 0, sum_even = 0;
 
    // Traverse the map
    Set<Map.Entry<Integer, Integer>> hmap = map.entrySet();
    for(Map.Entry<Integer, Integer> data:hmap)
    {
        int key = data.getKey();
        int val = data.getValue();
         
        // If frequency is odd
        if (val % 2 != 0)
         
            // Add sum of all occurrences of
            // current element to sum_odd
            sum_odd += (key) * (val);
 
        // If frequency is even
        if (val % 2 == 0)
         
            // Add sum of all occurrences of
            // current element to sum_even
            sum_even += (key) * (val);
    }
     
    // Calculate difference
    // between their sum
    int diff = sum_even - sum_odd;
 
    // Return diff
    return diff;
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 1, 5, 5, 2, 4, 3, 3 };
    int N = arr.length;
     
    System.out.println(findSum(arr, N));
}
}
 
// This code is contributed by jyoti369
 
 

Python3




# Python3 program to find absolute difference
# between the sum of all odd frequent and
# even frequent elements in an array
 
# Function to find the sum of all even
# and odd frequent elements in an array
def findSum(arr, N):
     
    # Stores the frequency of array elements
    mp = {}
     
    # Traverse the array
    for i in range(0, N):
         
        # Update frequency of
        # current element
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Stores sum of odd and even
    # frequent elements
    sum_odd, sum_even = 0, 0
     
    # Traverse the map
    for itr in mp:
         
        # If frequency is odd
        if (mp[itr] % 2 != 0):
             
            # Add sum of all occurrences of
            # current element to sum_odd
            sum_odd += (itr) * (mp[itr])
             
        # If frequency is even
        if (mp[itr] % 2 == 0):
             
            # Add sum of all occurrences of
            # current element to sum_even
            sum_even += (itr) * (mp[itr])
             
    # Calculate difference
    # between their sum
    diff = sum_even - sum_odd
     
    # Return diff
    return diff
 
# Driver code
arr = [ 1, 5, 5, 2, 4, 3, 3 ]
N = len(arr)
 
print(findSum(arr, N))
 
# This code is contributed by divyeshrabadiya07
 
 

C#




// C# program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find the sum of all even
    // and odd frequent elements in an array
    static int findSum(int[] arr, int N)
    {
        // Stores the frequency of array elements
        Dictionary<int, int> mp = new Dictionary<int, int>();
      
        // Traverse the array
        for (int i = 0; i < N; i++) {
      
            // Update frequency of
            // current element
            if(mp.ContainsKey(arr[i]))
            {
                mp[arr[i]]++;
            }
            else{
                mp[arr[i]] = 1;
            }
        }
      
        // Stores sum of odd and even
        // frequent elements
        int sum_odd = 0, sum_even = 0;
      
        // Traverse the map
        foreach(KeyValuePair<int, int> itr in mp) {
      
            // If frequency is odd
            if (itr.Value % 2 != 0)
      
                // Add sum of all occurrences of
                // current element to sum_odd
                sum_odd += (itr.Key)
                        * (itr.Value);
      
            // If frequency is even
            if (itr.Value % 2 == 0)
      
                // Add sum of all occurrences of
                // current element to sum_even
                sum_even += (itr.Key)
                            * (itr.Value);
        }
      
        // Calculate difference
        // between their sum
        int diff = sum_even - sum_odd;
      
        // Return diff
        return diff;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 1, 5, 5, 2, 4, 3, 3 };
    int N = arr.Length;
    Console.Write(findSum(arr, N));
  }
}
 
// This code is contributed by divyesh072019.
 
 

Javascript




<script>
 
// JavaScript program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
 
// Function to find the sum of all even
// and odd frequent elements in an array
function findSum(arr, N)
{
    // Stores the frequency of array elements
    var mp = {};
    for(let i =0; i<N;i++)
      mp[arr[i]] = 0;
 
    // Traverse the array
    for (let i = 0; i < N; i++) {
 
        // Update frequency of
        // current element
        mp[arr[i]]++;
    }
 
    // Stores sum of odd and even
    // frequent elements
    var sum_odd = 0, sum_even = 0;
 
 
    // Traverse the map
    for (let itr in mp) {
      
 
        // If frequency is odd
        if (mp[itr] % 2 != 0) {
 
            // Add sum of all occurrences of
            // current element to sum_odd
            sum_odd += (itr)
                    * (mp[itr]);
                 
        }
 
        // If frequency is even
        if (mp[itr] % 2 == 0) {
 
            // Add sum of all occurrences of
            // current element to sum_even
            sum_even += (itr)
                        * (mp[itr]);
                       
        }
                         
    }
 
    // Calculate difference
    // between their sum
    var diff = sum_even - sum_odd;
 
    // Return diff
    return diff;
}
 
// Driver Code
 
var arr = new Array( 1, 5, 5, 2, 4, 3, 3 );
var N = arr.length;
console.log( findSum(arr, N) );
 
// This code is contributed by ukasp. 
 
</script>
 
 
Output
9

Time Complexity: O(N)
Auxiliary Space: O(N)

Approach without using extra space:

  • We can just sort the array
  • After sorting all same time off elements will be adjacent to each other
  • We can count the frequency of a element and add the element according to the odd or even frequency

Implementation:-

C++




// C++ program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of all even
// and odd frequent elements in an array
int findSum(int arr[], int N)
{
      //sorting the array
      sort(arr,arr+N);
       
      //taking the first element as initial element
      //and frequency as 1
      int freq=1,element=arr[0];
   
      //to store sum of odd time and
      //even time present elements
      int odd_sum=0,even_sum=0;
   
      //traversing the array from second element
      for(int i=1;i<N;i++)
    {
          //if another element found
          if(arr[i]!=element)
        {
              //if previous element frequency was odd
              if(freq%2){
                  odd_sum+=freq*element;
            }
              else{
                  even_sum+=freq*element;
            }
               
              //setting frequency of new element as 1
              freq=1;
              element=arr[i];
        }
          else freq++;
    }
       
    //if last element frequency was odd
    if(freq%2){
      odd_sum+=freq*element;
    }
    else{
      even_sum+=freq*element;
    }
      return abs(odd_sum-even_sum);
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 5, 5, 2, 4, 3, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << findSum(arr, N);
 
    return 0;
}
//This code contributed by shubhamrajput6156
 
 

Java




import java.util.*;
 
public class Main {
     
    // Function to find the sum of all even
    // and odd frequent elements in an array
    static int findSum(int[] arr, int N)
    {
        //sorting the array
        Arrays.sort(arr);
         
        //taking the first element as initial element
        //and frequency as 1
        int freq=1,element=arr[0];
 
        //to store sum of odd time and
        //even time present elements
        int odd_sum=0,even_sum=0;
 
        //traversing the array from second element
        for(int i=1;i<N;i++)
        {
            //if another element found
            if(arr[i]!=element)
            {
                //if previous element frequency was odd
                if(freq%2 == 1){
                    odd_sum+=freq*element;
                }
                else{
                    even_sum+=freq*element;
                }
 
                //setting frequency of new element as 1
                freq=1;
                element=arr[i];
            }
            else freq++;
        }
 
        //if last element frequency was odd
        if(freq%2 == 1){
            odd_sum+=freq*element;
        }
        else{
            even_sum+=freq*element;
        }
        return Math.abs(odd_sum-even_sum);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 5, 5, 2, 4, 3, 3 };
        int N = arr.length;
        System.out.println(findSum(arr, N));
 
    }
}
 
 

Python3




# python program to find absolute difference
# between the sum of all odd frequent and
# even frequent elements in an array
 
# Function to find the sum of all even
# and odd frequent elements in an array
def find_sum(arr, N):
   
    # Sorting the array
    arr.sort()
     
    # Taking the first element as initial element
    # and frequency as 1
    freq = 1
    element = arr[0]
     
    # To store sum of odd time and
    # even time present elements
    odd_sum = 0
    even_sum = 0
     
    # Traversing the array from second element
    for i in range(1, N):
       
        # If another element found
        if arr[i] != element:
           
            # If previous element frequency was odd
            if freq % 2:
                odd_sum += freq * element
            else:
                even_sum += freq * element
                 
            # Setting frequency of new element as 1
            freq = 1
            element = arr[i]
        else:
            freq += 1
             
    # If last element frequency was odd
    if freq % 2:
        odd_sum += freq * element
    else:
        even_sum += freq * element
    return abs(odd_sum - even_sum)
 
# Driver Code
if __name__ == "__main__":
    arr = [1, 5, 5, 2, 4, 3, 3]
    N = len(arr)
    print(find_sum(arr,N))
 
 

C#




using System;
 
public class Program
{
  // Function to find the sum of all even
  // and odd frequent elements in an array
  public static int FindSum(int[] arr, int N)
  {
    // sorting the array
    Array.Sort(arr);
 
    // taking the first element as initial element
    // and frequency as 1
    int freq = 1, element = arr[0];
 
    // to store sum of odd time and
    // even time present elements
    int odd_sum = 0, even_sum = 0;
 
    // traversing the array from second element
    for (int i = 1; i < N; i++)
    {
      // if another element found
      if (arr[i] != element)
      {
        // if previous element frequency was odd
        if (freq % 2 != 0)
        {
          odd_sum += freq * element;
        }
        else
        {
          even_sum += freq * element;
        }
 
        // setting frequency of new element as 1
        freq = 1;
        element = arr[i];
      }
      else
      {
        freq++;
      }
    }
 
    // if last element frequency was odd
    if (freq % 2 != 0)
    {
      odd_sum += freq * element;
    }
    else
    {
      even_sum += freq * element;
    }
 
    return Math.Abs(odd_sum - even_sum);
  }
 
  // Driver Code
  public static void Main()
  {
    int[] arr = { 1, 5, 5, 2, 4, 3, 3 };
    int N = arr.Length;
    Console.WriteLine(FindSum(arr, N));
  }
}
 
 

Javascript




//Javascript program to find absolute difference
// between the sum of all odd frequent and
// even frequent elements in an array
 
// Function to find the sum of all even
// and odd frequent elements in an array
function find_sum(arr, N) {
 
  // Sorting the array
  arr.sort();
 
  // Taking the first element as initial element
  // and frequency as 1
  let freq = 1;
  let element = arr[0];
 
  // To store sum of odd time and
  // even time present elements
  let odd_sum = 0;
  let even_sum = 0;
 
  // Traversing the array from second element
  for (let i = 1; i < N; i++) {
 
    // If another element found
    if (arr[i] !== element) {
 
      // If previous element frequency was odd
      if (freq % 2) {
        odd_sum += freq * element;
      } else {
        even_sum += freq * element;
      }
 
      // Setting frequency of new element as 1
      freq = 1;
      element = arr[i];
    } else {
      freq++;
    }
  }
 
  // If last element frequency was odd
  if (freq % 2) {
    odd_sum += freq * element;
  } else {
    even_sum += freq * element;
  }
  return Math.abs(odd_sum - even_sum);
}
 
// Driver Code
  let arr = [1, 5, 5, 2, 4, 3, 3];
  let N = arr.length;
  console.log(find_sum(arr,N));
 
 
Output
9

Time Complexity:- O(NlogN)

Auxiliary Space:- O(1)



Next Article
Maximum difference between sum of even and odd indexed elements of a Subarray
author
patelajeet
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • Technical Scripter
  • frequency-counting
  • Technical Scripter 2020
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

Similar Reads

  • Difference between sum of K maximum even and odd array elements
    Given an array arr[] and a number K, the task is to find the absolute difference of the sum of K maximum even and odd array elements.Note: At least K even and odd elements are present in the array respectively. Examples: Input arr[] = {1, 2, 3, 4, 5, 6}, K = 2Output: 2Explanation:The 2 maximum even
    8 min read
  • Absolute Difference of even and odd indexed elements in an Array
    Given an array of integers arr, the task is to find the running absolute difference of elements at even and odd index positions separately. Note: 0-based indexing is considered for the array. That is the index of the first element in the array is zero. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Out
    6 min read
  • Maximum difference between sum of even and odd indexed elements of a Subarray
    Given an array nums[] of size N, the task is to find the maximum difference between the sum of even and odd indexed elements of a subarray.  Examples: Input: nums[] = {1, 2, 3, 4, -5}Output: 9Explanation: If we select the subarray {4, -5} the sum of even indexed elements is 4 and odd indexed element
    11 min read
  • Sum of all odd frequency elements in an array
    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,
    8 min read
  • Maximize difference between sum of even and odd-indexed elements of a subsequence
    Given an array arr[] consisting of N positive integers, the task is to find the maximum possible difference between the sum of even and odd-indexed elements of a subsequence from the given array. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9 } Output: 15 Explanation: Considering the subseq
    7 min read
  • Difference between sums of odd and even digits
    Given a long integer, we need to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit). Examples: Input: 1212112Output: YesExplanation:the odd position element is 2+2+1=5the even position element is 1+1+1+2=5t
    3 min read
  • Minimize increments required to make differences between all pairs of array elements even
    Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4
    5 min read
  • Maximize difference between sum of even and odd-indexed elements of a subsequence | Set 2
    Given an array arr[] consisting of N positive integers, the task is to find the maximum value of the difference between the sum of elements at even and odd indices for any subsequence of the array. Note: The value of N is always greater than 1. Examples: Input: arr[] = { 3, 2, 1, 4, 5, 2, 1, 7, 8, 9
    11 min read
  • Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array
    Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices & the count of odd elements at odd indices. Consider 1-based indexing Examples: Input: arr[] = {3, 4, 1, 5}Output: 0Explanation: Sum of even elements at even i
    5 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