Sort elements by frequency | Set 4 (Efficient approach using hash)
Last Updated :
02 Jun, 2023
Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first.
Examples:
Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6}
Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}
We have discussed different approaches in below posts :
Sort elements by frequency | Set 1
Sort elements by frequency | Set 2
Sorting Array Elements By Frequency | Set 3 (Using STL)
All of the above approaches work in O(n Log n) time where n is total number of elements. In this post, a new approach is discussed that works in O(n + m Log m) time where n is total number of elements and m is total number of distinct elements.
The idea is to use hashing.
- We insert all elements and their counts into a hash. This step takes O(n) time where n is number of elements.
- We copy the contents of hash to an array (or vector) and sort them by counts. This step takes O(m Log m) time where m is total number of distinct elements.
- For maintaining the order of elements if the frequency is the same, we use another hash which has the key as elements of the array and value as the index. If the frequency is the same for two elements then sort elements according to the index.
The below image is a dry run of the above approach:

We do not need to declare another map m2, as it does not provide the proper expected result for the problem.
instead, we need to just check for the first values of the pairs sent as parameters in the sortByVal function.
Below is the implementation of the above approach:
C++
// CPP program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Used for sorting by frequency. And if frequency is same,
// then by appearance
bool sortByVal(const pair<int, int>& a,
const pair<int, int>& b)
{
// If frequency is same then sort by index
if (a.second == b.second)
return a.first < b.first;
return a.second > b.second;
}
// function to sort elements by frequency
vector<int>sortByFreq(int a[], int n)
{
vector<int>res;
unordered_map<int, int> m;
vector<pair<int, int> > v;
for (int i = 0; i < n; ++i) {
// Map m is used to keep track of count
// of elements in array
m[a[i]]++;
}
// Copy map to vector
copy(m.begin(), m.end(), back_inserter(v));
// Sort the element of array by frequency
sort(v.begin(), v.end(), sortByVal);
for (int i = 0; i < v.size(); ++i)
while(v[i].second--)
{
res.push_back(v[i].first);
}
return res;
}
// Driver program
int main()
{
int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = sizeof(a) / sizeof(a[0]);
vector<int>res;
res = sortByFreq(a, n);
for(int i = 0;i < res.size(); i++)
cout<<res[i]<<" ";
return 0;
}
Python3
# Used for sorting by frequency. And if frequency is same,
# then by appearance
from functools import cmp_to_key
def sortByVal(a,b):
# If frequency is same then sort by index
if (a[1] == b[1]):
return a[0] - b[0]
return b[1] - a[1]
# function to sort elements by frequency
def sortByFreq(a, n):
res = []
m = {}
v = []
for i in range(n):
# Map m is used to keep track of count
# of elements in array
if(a[i] in m):
m[a[i]] = m[a[i]]+1
else:
m[a[i]] = 1
for key,value in m.items():
v.append([key,value])
# Sort the element of array by frequency
v.sort(key = cmp_to_key(sortByVal))
for i in range(len(v)):
while(v[i][1]):
res.append(v[i][0])
v[i][1] -= 1
return res
# Driver program
a = [ 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 ]
n = len(a)
res = []
res = sortByFreq(a, n)
for i in range(len(res)):
print(res[i],end = " ")
# This code is contributed by shinjanpatra
Java
// Java program for the above approach
import java.util.*;
// Used for sorting by frequency. And if frequency is same,
// then by appearance
class SortByValue implements Comparator<Map.Entry<Integer, Integer> >
{
// Used for sorting in descending order of values
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
// If frequency is same then sort by index
if (o1.getValue() == o2.getValue())
return o1.getKey() - o2.getKey();
return o2.getValue() - o1.getValue();
}
}
class GFG
{
// Function to sort elements by frequency
static Vector<Integer> sortByFreq(int a[], int n)
{
// Map to store the frequency of the elements
HashMap<Integer, Integer> m = new HashMap<>();
// Vector to store the sorted elements
Vector<Integer> v = new Vector<>();
// Insert elements and their frequency in the map
for (int i = 0; i < n; i++)
{
int x = a[i];
if (m.containsKey(x))
m.put(x, m.get(x) + 1);
else
m.put(x, 1);
}
// Copy map to vector
Vector<Map.Entry<Integer, Integer> > v1 =
new Vector<>(m.entrySet());
// Sort the vector elements by frequency
Collections.sort(v1, new SortByValue());
// Traverse the vector and insert elements
// in the vector v
for (int i = 0; i < v1.size(); i++)
for (int j = 0; j < v1.get(i).getValue(); j++)
v.add(v1.get(i).getKey());
return v;
}
// Driver program
public static void main(String[] args)
{
int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = a.length;
Vector<Integer> v = sortByFreq(a, n);
// Print the elements of vector
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}
JavaScript
<script>
// JavaScript program for the above approach
// Used for sorting by frequency. And if frequency is same,
// then by appearance
function sortByVal(a,b)
{
// If frequency is same then sort by index
if (a[1] == b[1])
return a[0] - b[0];
return b[1] - a[1];
}
// function to sort elements by frequency
function sortByFreq(a, n)
{
let res = [];
let m = new Map();
let v = [];
for (let i = 0; i < n; ++i) {
// Map m is used to keep track of count
// of elements in array
if(m.has(a[i]))
m.set(a[i],m.get(a[i])+1);
else
m.set(a[i],1);
}
for(let [key,value] of m){
v.push([key,value]);
}
// Sort the element of array by frequency
v.sort(sortByVal)
for (let i = 0; i < v.length; ++i)
while(v[i][1]--)
{
res.push(v[i][0]);
}
return res;
}
// Driver program
let a = [ 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 ];
let n = a.length;
let res = [];
res = sortByFreq(a, n);
for(let i = 0;i < res.length; i++)
document.write(res[i]," ");
// This code is contributed by shinjanpatra
</script>
C#
using System;
using System.Collections.Generic;
using System.Linq;
// Used for sorting by frequency. And if frequency is same,
// then by appearance
class SortByValue : IComparer<KeyValuePair<int, int>>
{
// Used for sorting in descending order of values
public int Compare(KeyValuePair<int, int> o1, KeyValuePair<int, int> o2)
{
// If frequency is same then sort by index
if (o1.Value == o2.Value)
return o1.Key - o2.Key;
return o2.Value - o1.Value;
}
}
class GFG
{
// Function to sort elements by frequency
static List<int> sortByFreq(int[] a, int n)
{
// Dictionary to store the frequency of the elements
Dictionary<int, int> m = new Dictionary<int, int>();
// List to store the sorted elements
List<int> res = new List<int>();
// Insert elements and their frequency in the dictionary
for (int i = 0; i < n; i++)
{
int x = a[i];
if (m.ContainsKey(x))
m[x]++;
else
m.Add(x, 1);
}
// Copy dictionary to list
List<KeyValuePair<int, int>> v =
new List<KeyValuePair<int, int>>(m);
// Sort the list elements by frequency
v.Sort(new SortByValue());
// Traverse the list and insert elements
// in the list v
foreach (KeyValuePair<int, int> kvp in v)
{
for (int i = 0; i < kvp.Value; i++)
res.Add(kvp.Key);
}
return res;
}
// Driver program
public static void Main(string[] args)
{
int[] a = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = a.Length;
List<int> res = sortByFreq(a, n);
// Print the elements of list
foreach (int i in res)
Console.Write(i + " ");
}
}
Output8 8 8 2 2 5 5 -1 6 9999999
Time Complexity: O(n) + O(m Log m) where n is total number of elements and m is total number of distinct elements
Auxiliary Space: O(n)
This article is contributed by Aarti_Rathi and Ankur Singh and improved by Ankur Goel.
Simple way to sort by frequency.
The Approach:
Here In This approach we first we store the element by there frequency in vector_pair format(Using Mapping stl map) then sort it according to frequency then reverse it and apply bubble sort to make the condition true decreasing frequency if 2 numbers have the same frequency then print the one which came first. then print the vector.
C++
#include <bits/stdc++.h>
#include<iostream>
using namespace std;
//map all the number and sort by frequency.
void the_helper(int a[],vector<pair<int,int>>&res,int n){
map<int,int>mp;
for(int i=0;i<n;i++)mp[a[i]]++;
for(auto it:mp)res.push_back({it.second,it.first});
sort(res.begin(),res.end());
}
int main() {
int a[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8};
vector<pair<int,int>>res;
the_helper(a,res,10);
reverse(res.begin(),res.end());
for(int i=0;i<res.size();i++){
if(res[i].first==res[i+1].first){
for(int j=i;j<res.size();j++){
if(res[i].second>res[j].second&&res[i].first==res[j].first){
swap(res[i],res[j]);
}
}
}
}
for(int i=0;i<res.size();i++){
for(int j=0;j<res[i].first;j++)cout<<res[i].second<<" ";
// cout<<endl;
}
return 0;
}
Java
// Java program for the above approach
import java.util.*;
// pair class
class Pair{
int first;
int second;
public Pair(int first, int second){
this.first = first;
this.second = second;
}
}
public class Main{
// map all the number and sort by frequency
public static void the_helper(int[] a, List<Pair> res, int n){
// create a new map to store the frequency of each number in the array
Map<Integer, Integer> mp = new HashMap<>();
for(int i = 0; i < n; i++){
// check if the map already has the number,
// if yes, increase its count by 1, else add it to the map with count 1
if(mp.containsKey(a[i]))
mp.put(a[i], mp.get(a[i])+1);
else
mp.put(a[i], 1);
}
// loop through the map entries and add them to the result list as pairs
for(Map.Entry<Integer, Integer> entry : mp.entrySet()){
res.add(new Pair(entry.getValue(), entry.getKey()));
}
// sort the result list in ascending order of
// frequency using a lambda expression
res.sort((x, y) -> x.first - y.first);
}
// driver program
public static void main(String[] args) {
int[] a = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8};
List<Pair> res = new ArrayList<>();
the_helper(a, res, 10);
// reverse the result list to get it in descending order of frequency
Collections.reverse(res);
// loop through the result list and swap pairs with
// equal frequencies if the second element of the earlier
// pair is greater than the second element of the later pair
for(int i = 0; i < res.size()-1; i++){
if(res.get(i).first == res.get(i+1).first){
for(int j = i; j < res.size(); j++){
if(res.get(i).second > res.get(j).second && res.get(i).first == res.get(j).first){
Pair temp = res.get(j);
res.set(j, res.get(i));
res.set(i, temp);
}
}
}
}
System.out.println();
// loop through the result list and print each pair's
//second element the number of times indicated by its first element
for(Pair p : res){
for(int i = 0; i < p.first; i++){
System.out.print(p.second + " ");
}
}
}
}
// this code is contributed by bhardwajji
Python3
# python3 program for the above approach
import collections
# map all the number and sort by frequency
def the_helper(a, res, n):
mp = collections.defaultdict(int)
for i in range(n):
mp[a[i]] += 1
for key, val in mp.items():
res.append((val, key))
res.sort()
# main function
if __name__ == '__main__':
a = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
res = []
the_helper(a, res, len(a))
res.reverse()
for i in range(len(res) - 1):
if res[i][0] == res[i+1][0]:
for j in range(i+1, len(res)):
if res[i][0] == res[j][0] and res[i][1] > res[j][1]:
res[i], res[j] = res[j], res[i]
for i in range(len(res)):
for j in range(res[i][0]):
print(res[i][1], end=' ')
# print() # uncomment to print each frequency on a new line
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
//map all the number and sort by frequency.
public static void the_helper(int[] a, List<Tuple<int,int>> res, int n) {
Dictionary<int,int> mp = new Dictionary<int,int>();
for (int i = 0; i < n; i++) {
if (mp.ContainsKey(a[i])) {
mp[a[i]]++;
} else {
mp[a[i]] = 1;
}
}
foreach (var it in mp) {
res.Add(new Tuple<int,int>(it.Value, it.Key));
}
res.Sort();
}
public static void Main() {
int[] a = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
List<Tuple<int,int>> res = new List<Tuple<int,int>>();
the_helper(a, res, 10);
res.Reverse();
for (int i = 0; i < res.Count; i++) {
if (i < res.Count - 1 && res[i].Item1 == res[i+1].Item1) {
for (int j = i; j < res.Count; j++) {
if (res[i].Item2 > res[j].Item2 && res[i].Item1 == res[j].Item1) {
var temp = res[i];
res[i] = res[j];
res[j] = temp;
}
}
}
}
for(int i=0;i<res.Count;i++){
for (int j = 0; j < res[i].Item1; j++) {
Console.Write(res[i].Item2 + " ");
}
}
}
}
JavaScript
// JavaScript program for the above approach
// pair class
class pair{
constructor(first, second){
this.first = first;
this.second = second;
}
}
// map all the number and sort by frequency
function the_helper(a, res, n){
mp = new Map();
for(let i = 0; i<n; i++){
if(mp.has(a[i]))
mp.set(a[i], mp.get(a[i])+1);
else
mp.set(a[i], 1);
}
mp.forEach(function(value, key){
res.push(new pair(value, key));
})
res.sort(function(a, b){
return a.first - b.first;
});
}
// driver program
let a = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8];
let res = [];
the_helper(a, res, 10);
res.reverse();
for(let i = 0; i < res.length-1; i++){
if(res[i].first == res[i+1].first){
for(let j = i; j < res.length; j++){
if(res[i].second > res[j].second && res[i].first == res[j].first){
let temp = res[j];
res[j] = res[i];
res[i] = temp;
}
}
}
}
console.log("\n");
for(let i = 0; i < res.length; i++){
for(let j = 0; j < res[i].first; j++){
console.log(res[i].second + " ");
}
}
// this code is contributed by Yash Agarwal(yashagarwal2852002)
Output8 8 8 2 2 5 5 -1 6 9999999
Time Complexity: O(n^2) I.e it take O(n) for getting the frequency sorted vector but for sorting in decreasing frequency if 2 numbers have the same frequency then print the one which came first we use bubble sort so it take O(n^2).
Auxiliary Space: O(n),for vector.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem