Problem · Array

Top K Frequent Elements

Learn this problem
Mediuminfosys logoinfosysFULLTIMEONSITE INTERVIEW

Problem statement

You are given an integer array nums and an integer k. Return the k distinct values that occur most frequently.

The selected set is guaranteed to be unique. For deterministic output, list selected values by decreasing frequency; when two selected values have the same frequency, list the smaller value first.

Function

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

Examples

Example 1

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

The frequencies are three for 1, two for 2, and one for 3.

Example 2

nums = [4,4,-1,-1,2]k = 2return = [-1,4]

Both selected values occur twice, so the smaller value comes first.

Constraints

  • 1 <= nums.length <= 100000
  • -10000 <= nums[i] <= 10000
  • 1 <= k <= the number of distinct values in nums.
  • The set of k most frequent values is unique.

More infosys problems

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