- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array with some elements where elements may appear multiple times. We have to sort the array such that elements are sorted according to their increase of frequency. So which element appears less number of time will come first and so on.

So, if the input is like nums = [1,5,3,1,3,1,2,5], then the output will be [2, 5, 5, 3, 3, 1, 1, 1]

To solve this, we will follow these steps −

mp := a new map

for each distinct element i from nums, do

x:= number of i present in nums

if x is present in mp, then

insert i at the end of mp[x]

otherwise mp[x] := a list with only one element i

ans:= a new list

for each i in sort the mp based on key, do

for each j in sort the list mp[i] in reverse order, do

insert j, i number of times into ans

return ans

Let us see the following implementation to get better understanding −

def solve(nums): mp = {} for i in set(nums): x=nums.count(i) try: mp[x].append(i) except: mp[x]=[i] ans=[] for i in sorted(mp): for j in sorted(mp[i], reverse=True): ans.extend([j]*i) return ans nums = [1,5,3,1,3,1,2,5] print(solve(nums))

[1,5,3,1,3,1,2,5]

[2, 5, 5, 3, 3, 1, 1, 1]

- Related Questions & Answers
- Sorting array of Number by increasing frequency JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Python - Sort rows by Frequency of K
- Python program to sort tuples by frequency of their absolute difference
- Python program to sort tuples in increasing order by any key.
- Python – Sort by Uppercase Frequency
- Sort Tuples in Increasing Order by any key in Python program
- Python – Sort Matrix by None frequency
- Python program to sort the elements of an array in ascending order
- Python program to sort the elements of an array in descending order
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Sort Characters By Frequency in C++
- Java Program to sort a subset of array elements
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript

Advertisements