Top K Frequent Elements
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Interview workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Interview workspace
Problem
Implement Solution.topKFrequent(nums, k). Return the k values with highest frequencies; output order is irrelevant and the answer set is unique.
Starter code
class Solution:
def topKFrequent(self, nums, k):
passTest cases
two-values
{
"args": [
[
1,
1,
1,
2,
2,
3
],
2
]
}Expected: [1,2]
Wizard outline
- Step 1: Initialize Solution.topKFrequent
Replace the empty starter with the first real state owned by Solution.topKFrequent. A small, named state is easier to verify than a complete algorithm. Establish it before adding the branch or loop that changes it.
- Step 2: Assemble the primary transition
Extend the initialized state with the next contiguous part of the popular solution. The transition explains how one input element or operation changes the state; boundaries are easier to reason about after this invariant is visible.
- Step 3: Pass the Single case
Complete the readable core algorithm for one representative Interview case. Use frequency as a bounded bucket index to avoid sorting every distinct key.
- Step 4: Harden the Two Values boundary
Repair the reviewed boundary and pass the complete submission contract. Each value appears in exactly the bucket equal to its frequency. Descending bucket traversal therefore visits values from highest frequency downward, and stopping at k returns exactly the required set.
Footguns and prerequisites
- Return values, not their frequency counts.
- hashing and sets
Reviewed references
Practice prerequisites
- Rank Top Words(opens in a new tab)
Selecting the first k entries after deterministic frequency ranking practices the candidate-ordering boundary in Top K Frequent Elements.
- Update a Bounded Heap(opens in a new tab)
Update a Bounded Heap isolates after each value, the heap contains the largest min(k, processed_count) values seen so far. That focused state discipline is required when implementing top k frequent elements as a complete Interview Problem.
Recommended approach and implementation
Count values, append each value to buckets[count], then scan bucket indices from len(nums) down until k values are collected.
Why it works: Each value appears in exactly the bucket equal to its frequency. Descending bucket traversal therefore visits values from highest frequency downward, and stopping at k returns exactly the required set.
class Solution:
def topKFrequent(self, nums, k):
"""
Checkpoint 1: initialize the state owned by this Interview contract.
Checkpoint 2: assemble the primary transition without hiding the boundary.
"""
counts = {}
for value in nums: counts[value] = counts.get(value, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for value, count in counts.items(): buckets[count].append(value)
output = []
for count in range(len(nums), 0, -1):
for value in buckets[count]:
output.append(value)
if len(output) == k: return output