Funcia
Lv.1countinghashsorting

Sort by Frequency

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

Return nums sorted so that more frequent values come first; values with the same frequency are ordered smaller first. Equal values are placed next to each other, as many times as they occur.

Examples

numsresult
[4, 6, 2, 6, 4, 4, 6][4, 4, 4, 6, 6, 6, 2]
[1, 1, 2, 2, 2, 3][2, 2, 2, 1, 1, 3]
[5, -1, 3][-1, 3, 5]

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(nums: int[]) → int[]

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000
  • −109≤-10^9 \le nums[i] ≤109\le 10^9

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

numsExpected
[4,6,2,6,4,4,6][4,4,4,6,6,6,2]
[1,1,2,2,2,3][2,2,2,1,1,3]
[5,-1,3][-1,3,5]

Hint

Hint

Count every value once with a hash map (or by sorting and grouping), sort the distinct values by (count desc, value asc) and expand each one count times: O(Nlog⁡N)O(N \log N). Counting each element's frequency by rescanning the array is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251696 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4010verdict only
performance603verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.