FastPrepTop K Frequent Elements

Top K Frequent Elements

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an integer array nums and k, return its k most frequent distinct values.

Order the returned values by decreasing frequency. When two values occur equally often, put the value whose first occurrence is earlier in nums first. Apply this same rule when a tie crosses the cutoff.

Return each selected value exactly once. A zero k returns an empty array. The input guarantees k does not exceed the number of distinct values. Implement the frequency-bucket optimization as well as a comparison-sort approach.

Function

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

Examples

Example 1

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

Value1 occurs three times and value2 twice.

Example 2

nums = [9,4,9,4,2]k = 2return = [9,4]

The tied values9 and4 occur twice;9 appeared first.

Example 3

nums = []k = 0return = []

An empty array permits only k=0.

Constraints

  • 0 <= nums.length <= 100000.
  • -1000000000 <= nums[i] <= 1000000000.
  • 0 <= k <= number of distinct values in nums.
  • Array positions are zero-based. Equal-frequency values are ordered by their first positions, not their numeric values.

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int[] topKFrequent(int[] nums, int k) {
    // write your code here
}
nums[1,1,1,2,2,3]
k2
expected[1,2]
Checking account…