Problem · Hash Table

Top K Frequent Elements

Learn this problem
EasyEricsson logoEricssonFULLTIMEONSITE INTERVIEW

Problem statement

Given an integer array nums and an integer k, return the k most frequent elements.

To make the output deterministic, sort elements by frequency in descending order. If two elements have the same frequency, the smaller numeric value comes first.

Function

solveTopKFrequentElements(nums: int[], k: int) → int[]

Complete solveTopKFrequentElements. It has the following parameters:

int[] nums: the input array

int k: the number of elements to return

Return an int[] containing the top k elements in the deterministic order described above.

Examples

Example 1

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

1 appears 3 times and 2 appears 2 times, so they are the two most frequent elements.

Example 2

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

Every number appears once, so ties are resolved by smaller value first.

Constraints

1 <= nums.length <= 10^5

-10^4 <= nums[i] <= 10^4

1 <= k <= number of distinct elements in nums

More Ericsson problems

drafts saved locally
public int[] solveTopKFrequentElements(int[] nums, int k) {
    // write your code here
}
nums[1,1,1,2,2,3]
k2
expected[1,2]
checking account