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 minimum absolute differences in an array
Next article icon

Sum of all minimum occurring elements in an Array

Last Updated : 05 Sep, 2022
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 least occurring elements in the given array. That is the sum of all such elements whose frequency is minimum in the array.
Examples: 

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

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 the minimum occurring element.
  • Now, to find the sum traverse the map again and for all elements with minimum frequency find frequency_of_min_occurring_element*min_occurring_element and find their sum.

Below is the implementation of the above approach: 

C++




// C++ program to find the sum of all minimum
// occurring elements in an array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of all minimum
// 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]]++;   
 
    // Find the min frequency
    int minFreq = INT_MAX;
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {
        if (itr->second < minFreq) {
            minFreq = itr->second;
        }
    }
 
    // Traverse the map again and find the sum
    int sum = 0;
    for (auto itr = mp.begin(); itr != mp.end(); itr++) {
        if (itr->second == minFreq) {
            sum += itr->first * itr->second;
        }
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 20, 30, 40, 40 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    cout << findSum(arr, N);
 
    return 0;
}
 
 

Java




// Java program to find the sum of all minimum
// occurring elements in an array
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
class GFG
{
// Function to find the sum of all minimum
// 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);
 
 
    // Find the min frequency
    int minFreq = Integer.MAX_VALUE;
    minFreq = Collections.min(mp.entrySet(),
            Comparator.comparingInt(Map.Entry::getKey)).getValue();
 
 
    // Traverse the map again and find the sum
    int sum = 0;
    for (Map.Entry<Integer,Integer> entry : mp.entrySet())
    {
        if (entry.getValue() == minFreq)
        {
            sum += entry.getKey() * entry.getValue();
        }
    }
 
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 10, 20, 30, 40, 40 };
 
    int N = arr.length;
 
    System.out.println( findSum(arr, N));
}
}
 
// This code contributed by Rajput-Ji
 
 

Python3




# Python3 program to find theSum of all
# minimum occurring elements in an array
import math as mt
 
# Function to find theSum of all minimum
# occurring elements in an array
def findSum(arr, N):
 
    # Store frequencies of elements
    # of the array
    mp = dict()
    for i in arr:
        if i in mp.keys():
            mp[i] += 1
        else:
            mp[i] = 1
 
    # Find the min frequency
    minFreq = 10**9
    for itr in mp:
        if mp[itr]< minFreq:
            minFreq = mp[itr]
         
    # Traverse the map again and
    # find theSum
    Sum = 0
    for itr in mp:
        if mp[itr]== minFreq:
            Sum += itr * mp[itr]
         
    return Sum
 
# Driver Code
arr = [ 10, 20, 30, 40, 40]
 
N = len(arr)
 
print(findSum(arr, N))
 
# This code is contributed by
# mohit kumar 29
 
 

C#




// C# program to find the sum of all minimum
// occurring elements in an array
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the sum of all minimum
// occurring elements in an array
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);
        }
    }
   
    // Find the min frequency
    int minFreq = Int32.MaxValue;
    foreach(KeyValuePair<int, int> itr in mp)
    {
        if (itr.Value < minFreq)
        {
            minFreq = itr.Value;
        }
    }
    
    // Traverse the map again and find the sum
    int sum = 0;
    foreach(KeyValuePair<int, int> itr in mp)
    {
        if (itr.Value == minFreq)
        {
            sum += itr.Key * itr.Value;
        }
    }
    return sum;
}
 
// Driver code
static void Main()
{
    int[] arr = { 10, 20, 30, 40, 40 };
 
    int N = arr.Length;
   
    Console.Write(findSum(arr, N));
}
}
 
// This code is contributed by divyeshrabadiya07
 
 

Javascript




<script>
 
// JavaScript program to find
// the sum of all minimum
// occurring elements in an array
 
// Function to find the sum of all minimum
// 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);
        }
    }
   
    // Find the min frequency
    let minFreq = Number.MAX_VALUE;
    for (let [key, value] of mp.entries())
    {
        if (value < minFreq)
        {
            minFreq = value;
        }
    }
   
    // Traverse the map again and find the sum
    let sum = 0;
    for (let [key, value] of mp.entries())
    {
        if (value == minFreq)
        {
            sum += key * value;
        }
    }
   
    return sum;
}
 
// Driver Code
let arr=[ 10, 20, 30, 40, 40 ];
let N = arr.length;
document.write(findSum(arr, N));
 
 
// This code is contributed by patel2127
 
</script>
 
 
Output: 
60

 

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

Auxiliary Space: O(N) because it is using unordered_map “mp”
 



Next Article
Sum of minimum absolute differences in an array

B

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

Similar Reads

  • Remove all occurrences of any element for maximum array sum
    Given an array of positive integers, remove all the occurrences of the element to get the maximum sum of the remaining array. Examples: Input : arr = {1, 1, 3} Output : 3 On removing 1 from the array, we get {3}. The total value is 3 Input : arr = {1, 1, 3, 3, 2, 2, 1, 1, 1} Output : 11 On removing
    6 min read
  • Minimum sum possible by removing all occurrences of any array element
    Given an array arr[] consisting of N integers, the task is to find the minimum possible sum of the array by removing all occurrences of any single array element. Examples: Input: N = 4, arr[] = {4, 5, 6, 6}Output: 9Explanation: All distinct array elements are {4, 5, 6}. Removing all occurrences of 4
    6 min read
  • Minimum operation to make all elements equal in array
    Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element. Examples: Input : arr[] = [1, 2, 3, 4]Output :
    11 min read
  • Sum of minimum absolute differences in an array
    Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
    8 min read
  • Find the minimum and maximum sum of N-1 elements of the array
    Given an unsorted array A of size N, the task is to find the minimum and maximum values that can be calculated by adding exactly N-1 elements. Examples: Input: a[] = {13, 5, 11, 9, 7} Output: 32 40 Explanation: Minimum sum is 5 + 7 + 9 + 11 = 32 and maximum sum is 7 + 9 + 11 + 13 = 40.Input: a[] = {
    10 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Sum of (maximum element - minimum element) for all the subsets of an array.
    Given an array arr[], the task is to compute the sum of (max{A} - min{A}) for every non-empty subset A of the array arr[].Examples: Input: arr[] = { 4, 7 } Output: 3There are three non-empty subsets: { 4 }, { 7 } and { 4, 7 }. max({4}) - min({4}) = 0 max({7}) - min({7}) = 0 max({4, 7}) - min({4, 7})
    10 min read
  • Sum of minimum elements of all subarrays
    Given an array A of n integers. The task is to find the sum of minimum of all possible (contiguous) subarray of A. Examples: Input: A = [3, 1, 2, 4] Output: 17 Explanation: Subarrays are [3], [1], [2], [4], [3, 1], [1, 2], [2, 4], [3, 1, 2], [1, 2, 4], [3, 1, 2, 4]. Minimums are 3, 1, 2, 4, 1, 1, 2,
    15+ min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
    9 min read
  • Minimum Cost to make all array elements equal using given operations
    Given an array arr[] of positive integers and three integers A, R, M, where The cost of adding 1 to an element of the array is A,the cost of subtracting 1 from an element of the array is R andthe cost of adding 1 to an element and subtracting 1 from another element simultaneously is M. The task is t
    12 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