Sum of all minimum occurring elements in an Array
Last Updated :
05 Sep, 2022
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>
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"
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read