347. Top K Frequent Elements
mediumAsked at Juniper NetworksReturn the k most frequent elements in an array. Juniper asks this in control-plane and telemetry roles where finding the top-k most-seen BGP prefixes, OSPF neighbors, or interface error codes in a data stream is a real operational problem — it tests both counting and efficient selection.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Juniper Networks loops.
- Glassdoor (2026-Q1)— Cited in Juniper SWE and data-engineering interview reports as a common top-k pattern problem.
- Blind (2025-11)— Juniper candidates list top-k frequency as a medium-difficulty must-prep problem.
Problem
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Constraints
1 <= nums.length <= 10^5−10^4 <= nums[i] <= 10^4k is in the range [1, the number of unique elements in the array].It is guaranteed that the answer is unique.
Examples
Example 1
nums = [1,1,1,2,2,3], k = 2[1,2]Explanation: 1 appears 3 times, 2 appears 2 times — the top 2.
Example 2
nums = [1], k = 1[1]Explanation: Only one unique element.
Approaches
1. Count + sort
Count frequencies with a Map, sort entries by frequency descending, take the first k.
- Time
- O(n log n)
- Space
- O(n)
function topKFrequent(nums, k) {
const count = new Map();
for (const n of nums) count.set(n, (count.get(n) || 0) + 1);
return [...count.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, k)
.map(([num]) => num);
}Tradeoff: O(n log n). Straightforward but sorting all elements is overkill when we only need k.
2. Bucket sort — O(n)
Frequencies range from 1 to n. Create n+1 buckets indexed by frequency. Put each number in its bucket. Iterate from the highest bucket downward to collect k elements.
- Time
- O(n)
- Space
- O(n)
function topKFrequent(nums, k) {
const count = new Map();
for (const n of nums) count.set(n, (count.get(n) || 0) + 1);
// buckets[i] = list of numbers with frequency i
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (const [num, freq] of count.entries()) {
buckets[freq].push(num);
}
const result = [];
for (let i = buckets.length - 1; i >= 1 && result.length < k; i--) {
for (const num of buckets[i]) {
result.push(num);
if (result.length === k) return result;
}
}
return result;
}Tradeoff: O(n) time and space. The bucket-sort insight: frequency is bounded by n, so we can use index-as-frequency without sorting. This is the optimal approach.
Juniper Networks-specific tips
Juniper interviewers will probe beyond O(n log n). State upfront: 'The sort approach works but I can do O(n) using bucket sort since the frequency is bounded by the input size.' This signals algorithmic sophistication. In telemetry contexts, connect the problem to: 'If I'm counting the top-k most-seen interface error codes over a time window, bucket sort keeps me at linear time even for millions of samples.'
Common mistakes
- Creating n buckets instead of n+1 — frequency n is valid (all elements are the same) and needs an index of n.
- Sorting the output — the problem says any order is acceptable; no need to sort.
- Using a max-heap — correct but O(n log k); mention it as an intermediate approach between sort and bucket sort.
- Initializing count.get(n) without a fallback — use || 0 or a default Map to avoid NaN.
Follow-up questions
An interviewer at Juniper Networks may pivot to one of these next:
- Top K Frequent Words (LC 692) — same problem but with strings, with lexicographic tiebreaking.
- Find K Closest Elements (LC 658) — find k elements closest to a target value.
- How would you compute top-k frequencies over a sliding window in a real-time stream?
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why use bucket sort instead of a heap?
Bucket sort is O(n) while a min-heap approach is O(n log k). When k is close to n, the heap's log k advantage disappears. Bucket sort is also simpler to implement here because frequency is naturally bounded by n.
Can two elements have the same frequency?
Yes, but the problem guarantees the answer is unique — meaning there is always a clear top-k. In a general setting you would need a tiebreaking rule.
What is the space complexity?
O(n) for the frequency map and the bucket array. Both are proportional to the number of distinct elements.
Practice these live with InterviewChamp.AI
Drill Top K Frequent Elements and other Juniper Networks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →