Skip to main content

12. Top K Frequent Elements

mediumAsked at Redis

Return the k most frequent integers; Redis uses it to probe bucket-sort and heap thinking, the same patterns powering Redis Streams XAUTOCLAIM and ZSET top-K queries.

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. Better than O(n log n) is expected.

Constraints

  • 1 <= nums.length <= 10^5
  • k is in [1, number of unique 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. Sort by frequency

Count, then sort entries by count desc.

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

Tradeoff:

2. Bucket sort by frequency

Place each value into a bucket indexed by its frequency (max n+1 buckets). Walk buckets from high to low collecting until k. This is the same pattern Redis ZADD uses on a frequency-indexed sorted set.

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

Tradeoff:

Redis-specific tips

Redis interviewers like the bucket-sort framing because it's how Redis ZADD groups members by score; if you mention OBJECT FREQ and LFU eviction sampling you'll earn a bonus.

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

Practice these live with InterviewChamp.AI →