Skip to content
Decoder

Top K Frequent Elements

Medium

Problem

Given a list of integers nums and a number k, return the **k values that appear most often**. You can return them in any order. Aim for better than O(n log n).

Example 1

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

Example 2

Input
nums = [4, 4, 4, 6, 6, 5], k = 1
Output
[4]

Example 3

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

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= the number of distinct values.
  • The answer is unique: there is no tie at the cut-off.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.