FastPrepFastPrep
Problem Brief

Top K Frequent Elements

FULLTIMEONSITE INTERVIEW

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 Description

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.

1Example 1

Input
nums = [1,1,1,2,2,3], k = 2
Output
[1,2]
Explanation

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

2Example 2

Input
nums = [4,5,2,1,3], k = 5
Output
[1,2,3,4,5]
Explanation

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

Constraints

Limits and guarantees your solution can rely on.

1 <= nums.length <= 10^5

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

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

public int[] solveTopKFrequentElements(int[] nums, int k) {
    // write your code here
}
Input

nums

[1,1,1,2,2,3]

k

2

Output

[1,2]

Sign in to submit your solution.