Funcia
Lv.2arrayhashsorting

Top K Frequent Numbers

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

Given an integer array nums and an integer k, return the k values that appear most often, ordered by frequency descending, and by value ascending among equal frequencies.

Examples

numskresult
[1, 1, 1, 2, 2, 3]2[1, 2]
[4, -1, 4, -1, 7]3[-1, 4, 7]
[9]1[9]

Efficiency

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

Function signature

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

Constraints

  • 1≤1 \le nums.length ≤200,000\le 200{,}000, −109≤-10^9 \le nums[i] ≤109\le 10^9
  • 1≤1 \le k ≤\le number of distinct values in nums

Expected complexity

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

Examples

numskExpected
[1,1,1,2,2,3]2[1,2]
[4,-1,4,-1,7]3[-1,4,7]
[9]1[9]

Hint

Hint

Count with a hash map, then sort the distinct values by (-count, value) and take the first k. Looking up each element in a plain list of distinct values is O(N⋅D)O(N \cdot D) 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 251588 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

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

No result yet. Run or submit your code.