Program to sort array by increasing frequency of elements in Python

PythonServer Side ProgrammingProgramming

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

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):
   mp = {}
   for i in set(nums):

   for i in sorted(mp):
      for j in sorted(mp[i], reverse=True):
   return ans

nums = [1,5,3,1,3,1,2,5]




[2, 5, 5, 3, 3, 1, 1, 1]
Published on 17-May-2021 13:07:42