Sorting elements by frequency is a common task in programming, where the goal is to reorder elements in a way that reflects their occurrences in the input. If two elements have the same frequency, the one that appears first in the input retains its position. This article explores multiple methods to solve this problem efficiently, covering sorting, hashing, and map-based approaches.
Given an array of integers, sort its elements in decreasing order of their frequency. If two elements have the same frequency, retain their relative order from the input.
Input:
2,3,2,4,5,12,2,3,3,3,122, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12
Output:
3,3,3,3,2,2,2,12,12,4,53, 3, 3, 3, 2, 2, 2, 12, 12, 4, 5
Input:
1,2,3,2,1,1,4,5,6,61, 2, 3, 2, 1, 1, 4, 5, 6, 6
Output:
1,1,1,2,2,6,6,3,4,51, 1, 1, 2, 2, 6, 6, 3, 4, 5
Time Complexity:
O(n2)O(n^2) due to nested loops for counting frequencies.
Time Complexity:
O(nlogn)O(n \log n) for sorting.
Time Complexity:
O(nlogn)O(n \log n) for map operations.
Input: 2,3,2,4,5,12,2,3,3,3,122, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12