Skip to main content

19. Top K Frequent Elements

mediumAsked at ByteDance

Return the k most frequent elements in an array — ByteDance uses it as a direct proxy for top-K trending content selection in TikTok feeds.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order, and the answer is guaranteed to be unique.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in [1, number of distinct elements]

Examples

Example 1

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

Example 2

Input
nums = [1], k = 1
Output
[1]

Approaches

1. Count, sort, take k

Build a frequency map, sort entries by count, slice the top k.

Time
O(n log n)
Space
O(n)
const c=new Map(); for(const x of nums) c.set(x,(c.get(x)||0)+1);
return [...c.entries()].sort((a,b)=>b[1]-a[1]).slice(0,k).map(([v])=>v);

Tradeoff:

2. Bucket sort by frequency

Build a frequency map, bucket values by frequency (1..n), then read buckets from highest down until k values are collected.

Time
O(n)
Space
O(n)
function topKFrequent(nums, k) {
  const count = new Map();
  for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
  const buckets = Array.from({ length: nums.length + 1 }, () => []);
  for (const [val, c] of count) buckets[c].push(val);
  const out = [];
  for (let f = buckets.length - 1; f > 0 && out.length < k; f--) {
    for (const v of buckets[f]) {
      out.push(v);
      if (out.length === k) break;
    }
  }
  return out;
}

Tradeoff:

ByteDance-specific tips

ByteDance interviewers love the bucket-sort framing because it mirrors how their trending-hashtag service partitions counts by frequency rather than full-sorting them.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Top K Frequent Elements and other ByteDance interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →