Skip to main content

23. Top K Frequent Elements

mediumAsked at Square

Surface the K most common payment failure codes from a transaction log — Square's Payments Risk team runs this query at dashboard refresh time to triage which error categories need immediate incident response.

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. Your algorithm must be better than O(n log n) time complexity.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • k is in the range [1, number of unique elements in the array]
  • The answer is guaranteed to be 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. Hash map + sort

Count frequencies with a map, sort by frequency descending, take first k. O(n log n) — violates the problem's complexity requirement.

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

Tradeoff:

2. Bucket sort (O(n))

Count frequencies; create buckets indexed by frequency (bucket[f] = list of nums with frequency f). Iterate buckets from high to low and collect k elements. O(n) time and space — meets the problem's requirement.

Time
O(n)
Space
O(n)
function topKFrequent(nums, k) {
  const freq = new Map();
  for (const n of nums) freq.set(n, (freq.get(n) || 0) + 1);
  const buckets = new Array(nums.length + 1).fill(null).map(() => []);
  for (const [num, f] of freq) buckets[f].push(num);
  const res = [];
  for (let i = buckets.length - 1; i >= 0 && res.length < k; i--) {
    res.push(...buckets[i]);
  }
  return res.slice(0, k);
}

Tradeoff:

Square-specific tips

The O(n log n) sort solution is the trap — the problem explicitly bans it. Square uses this to see whether you push toward bucket sort on your own or wait to be led. Name the approach before coding it: 'because frequency is bounded by array length, I can use the frequency as an array index.' That single sentence demonstrates the key insight clearly.

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

Practice these live with InterviewChamp.AI →