Given an integer array, sort its element by their frequency and index. i.e., if two elements have different frequencies, then the one which has more frequency should come first; otherwise, the one which has less index should come first.

For example,

Input : [3, 3, 1, 1, 1, 8, 3, 6, 8, 7, 8]
 
Output: [3, 3, 3, 1, 1, 1, 8, 8, 8, 6, 7]

Practice this problem

The idea is to write a custom comparison method to solve this problem. Let the two elements to be compared are x and y. Then

  1. If x and y have different frequencies, then the one with more frequency should be treated as smaller than the other.
  2. If x and y have the same frequencies, then the one with less index should be treated as smaller than the other.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

3 3 3 1 1 1 8 8 8 6 7

Java


Download  Run Code

Output:

[3, 3, 3, 1, 1, 1, 8, 8, 8, 6, 7]

Python


Download  Run Code

Output:

[3, 3, 3, 1, 1, 1, 8, 8, 8, 6, 7]

The time complexity of the above solution is O(n + m.log(m)) and requires O(m) extra space, where n is the size of the input and m is the total number of distinct elements in the input.