Count frequencies, then bucket sort by count. Scan from highest bucket to collect top k.
function topKFrequent(nums, k): count = Counter(nums) buckets = [[] for _ in range(len(nums) + 1)] for num, freq in count.items(): buckets[freq].append(num) result = [] for i in range(len(buckets) - 1, -1, -1): for num in buckets[i]: result.append(num) if len(result) == k: return result return result
time, space.