Top K Frequent Elements

Arrays & Hashing, problem 5 of 9

Top K Frequent Elements

Medium

LC #347

hash mapcountingbucket sort

Not attempted yet

Given an integer list nums and an integer k, return the k values that appear most often. Return them in any order.

The answer is guaranteed to be unique (no ties at the cut-off). Try to beat O(n log n).

Example 1

Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]

Example 2

Input: nums = [1], k = 1
Output: [1]

Example 3

Input: nums = [4, 1, -1, 2, -1, 2, 3], k = 2
Output: [-1, 2]

Constraints

  • 1 ≤ len(nums) ≤ 2 · 10^5
  • 1 ≤ k ≤ number of distinct values

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.