Space
Open
From Fieldwork
Scales
Archive
Used for: K Closest Points to Origin, Top K Frequent Elements.
Visual Logic: If you want the Top K Largest, use a Min-Heap. Keep the heap size fixed at K. If a new number is bigger than the smallest guy in the VIP section (the root of the min-heap), kick the small guy out and let the new guy in.
import heapq
def top_k_elements(nums, k):
# 1. Count frequencies (if needed)
count = {} # create hashmap of frequencies
# 2. The Heap
heap = [] # Min-heap stores (frequency, value)
for num, freq in count.items():
# Push into heap
heapq.heappush(heap, (freq, num))
# 3. Maintain size K
if len(heap) > k:
heapq.heappop(heap) # Removes the SMALLEST frequency
return [val for freq, val in heap]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