InferenceAI

Enter at least two characters to search.

Start free

Top K Frequent Values

mediumArrays & Hashing25 min25 XP

Return the k most frequent values in nums, ordered by frequency (highest first), breaking ties by the smaller value first.

Requirements

  • Bucket sort by frequency gives O(n)O(n); a heap gives O(nlog⁡k)O(n \log k).

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[1,1,1,2,2,3],2]
TASKtop_k_frequent_values()
EXPECTED OUTPUT[1,2]

Start with the input values shown in this example.

Example 1 of 3

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

Output: [1,2]

Explanation: classic

Input: nums = [1], k = 1

Output: [1]

Explanation: single

Input: nums = [4,4,5,5,6], k = 2

Output: [4,5]

Explanation: tie

Hint 1

Count with a Counter, then sort the distinct values by (-count, value) or use bucket lists indexed by count.

Topics

DSAArrays & HashingPython