Space
Open
From Fieldwork
Scales
Archive
Bucket sort
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
# Create buckets where index = frequency
# Size is len(nums) + 1 because max frequency is len(nums)
freq = [[] for _ in range(len(nums) + 1)]
# 1. Count frequencies
for n in nums:
count[n] = count.get(n, 0) + 1
# 2. Fill buckets: index is frequency, value is list of numbers
for n, c in count.items():
freq[c].append(n)
# 3. Iterate backwards (highest frequency first) to collect k elements
res = []
for i in range(len(freq) - 1, 0, -1):
for n in freq[i]:
res.append(n)
if len(res) == k:
return res
return resHeap and frequency map
from collections import Counter
import heapq
from typing import List
def topKFrequent(nums: List[int], k: int) -> List[int]:
# 1. Build the frequency map: O(N)
count = Counter(nums)
# 2. Use a heap to find the k largest frequent elements: O(N log k)
# heapq.nlargest optimizes this process internally
return heapq.nlargest(k, count.keys(), key=count.get)Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode