Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-092

Top K Frequent Elements

Problem

Return the k values that appear most often in nums.

Count frequencies with a dictionary, then order values by descending count and break ties by ascending value so the output is deterministic. Return an empty list when k is 0.

Hint

Sort by the tuple (negative frequency, value) for a stable, deterministic order.

Test cases

case 1
in: [[1,1,1,2,2,3],2]
expected: [1,2]
case 2
in: [[1],1]
expected: [1]
case 3
in: [[4,4,4,2,2,3,3,3],2]
expected: [3,4]
case 4
in: [[1,2,3],3]
expected: [1,2,3]
case 5
in: [[5,5],1]
expected: [5]
Starter codePython
def top_k_frequent(nums, k):
    # Your code here
    pass

5 test cases · run your code against them in the editor