Menu
CoddyTech

Top K Frequent Elements

MediumHeapHashingpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums and an integer k. Return the k values that occur most often in nums, the most frequent first. When two values occur the same number of times, the smaller value comes first.

Each value appears once in the answer, however often it occurs in nums, and k is never larger than the number of different values.

Function

topKFrequent(nums: integer-array, k: integer) → integer-array
numsinteger-array
the values to count
kinteger
how many values to return
Returnsinteger-array
the k most frequent values, most frequent first, the smaller value first on a tie

Constraints

  • 1 ≤ nums.length ≤ 104
  • -104 ≤ nums[i] ≤ 104
  • 1 ≤ k, and k is at most the number of distinct values in nums.

Examples

Input
nums = [4, 1, 4, 2, 1, 4, 3, 1, 4]k = 2
Output
[4, 1]
Explanation
4 occurs four times, 1 three times, and 2 and 3 once each. The two most frequent values are 4, then 1.

lock icon+16 hidden tests on Submit

Reset code
def topKFrequent(nums, k):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [4, 1, 4, 2, 1, 4, 3, 1, 4]
k = 2

Expected

[4, 1]