Mid-levelMid (3–6 yrs)CodingPythonAmazonMetaNetflix
Top K Frequent Elements
Return the k most frequent elements from an integer array. Order among ties may be arbitrary unless specified.
Answers use simple, clear English.
Time: O(n log k)Space: O(n)
Quick interview answer
Count frequencies with a hash map, then use a min-heap of size k (or bucket sort by frequency). Heap approach is O(n log k); bucket sort is O(n) when values allow.
Detailed answer
Count frequencies with a hash map, then use a min-heap of size k (or bucket sort by frequency). Heap approach is O(n log k); bucket sort is O(n) when values allow. Clarify whether stable ordering by value is required.
Full explanation
Clarify whether stable ordering by value is required.
Real example & use case
Trending hashtags dashboard showing the top-k tags in the last hour.
Pros & cons
Pros: heap scales with k. Cons: bucket sort needs bounded frequency range insight.
Code example
import heapq
from collections import Counter
def top_k_frequent(nums: list[int], k: int) -> list[int]:
counts = Counter(nums)
return [x for x, _ in heapq.nlargest(k, counts.items(), key=lambda kv: kv[1])]Practice code · python (view only · no execution)
import heapq
from collections import Counter
def top_k_frequent(nums: list[int], k: int) -> list[int]:
counts = Counter(nums)
return [x for x, _ in heapq.nlargest(k, counts.items(), key=lambda kv: kv[1])]#heap#hashmap