FastPrepTop K Frequent Elements
Problems/Top K Frequent Elements

Top K Frequent Elements

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report asks for K most frequent elements and an optimization using bucket sort. This practice version uses integers and orders tied frequencies by first appearance; the tie rule, interface, limits and zero-k behavior were not reported. Approximate source match: 85%.

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]

Value 1 occurs three times and value 2 twice.

Example 2

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

The tied values 9 and 4 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

  • Integer Compression OffsetPHONE SCREEN · Seen Oct 2026
  • Array Interval SumsOA · Seen Oct 2026
  • Job Runner Chain ReportsOA · Seen Oct 2026
All Headlands Technologies interview questionsSee Headlands Technologies hiring insights
Saved
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        // write your code here
    }
}
Checking account…