Skip to main content

17. Top K Frequent Elements

mediumAsked at Flipkart

Return the k most frequent values in an array — Flipkart maps this to surfacing the top-K trending SKUs during a Big Billion Days sale event.

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 algorithm must run in better than O(n log n) time.

Constraints

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

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. Sort frequencies

Count, sort entries by count descending, return top k keys.

Time
O(n log n)
Space
O(n)
// fails the better-than-n-log-n target

Tradeoff:

2. Bucket sort by frequency

Count occurrences; place each value into a bucket indexed by frequency (1..n). Walk buckets from high to low and collect k values. Linear time, no comparison sort.

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

Tradeoff:

Flipkart-specific tips

Flipkart panels reward the bucket-sort framing — they use the same trick for top-N trending product surfaces inside marketplace search ranking.

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 Flipkart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →