#C867. Rearrange Array by Frequency
Rearrange Array by Frequency
Rearrange Array by Frequency
You are given an array of integers. Your task is to rearrange the array such that all the occurrences of the element with the highest frequency come first, then the occurrences of the element with the next highest frequency, and so on.
If two elements have the same frequency, their relative order should follow their first appearance in the original array.
Formally, for each distinct element \( x \), let \( f(x) \) denote its frequency in the array. The array should be rearranged so that if \( x \) appears before \( y \) in the sorted array then either \( f(x) > f(y) \) or \( f(x) = f(y) \) and the first appearance index of \( x \) in the original array is less than that of \( y \).
inputFormat
The first line of input contains a single integer \( n \) (\( 1 \leq n \leq 10^5 \)), representing the number of elements in the array.
The second line contains \( n \) space-separated integers representing the elements of the array.
outputFormat
Output the rearranged array in one line. The elements should be separated by a space.
## sample6
4 5 6 5 4 3
5 5 4 4 6 3
</p>