Lv.1countinghashsorting
Sort by Frequency
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 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
| nums | result |
|---|---|
[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
-
nums.length -
nums[i]
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| nums | Expected |
|---|---|
[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: . Counting each element's frequency by rescanning the array is and
exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1696 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 3 | verdict only |