Back to Practice
#0035

Top K Frequent Values

MediumDSA20 min15 XP

Problem

Given nums and k, return the k values with highest frequency. If frequencies tie, smaller values should come first.

Why This Matters

Top-k frequency appears in search suggestions, logs, recommendation features, and classic coding interviews.

Function Signature

def top_k_frequent(nums, k):

Examples

Example 1
Inputnums = [1,1,1,2,2,3], k = 2
Output[1, 2]

1 appears three times and 2 appears twice.

Constraints

  • k is at least 1.
  • k is no larger than the number of unique values.
  • Tie-break by smaller value first.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Classic top two
Input[1,1,1,2,2,3], 2
Expected[1, 2]

The two highest frequencies belong to 1 and 2.

Tie by value
Input[4,4,2,2,3], 2
Expected[2, 4]

2 and 4 tie with frequency 2, so smaller value comes first.

Hidden Test Categories
k equals number of unique valuesNegative numbersSingle unique valueLarge repeated input