Top k frequent elements
- CH1 heap
Count first, then keep the k most frequent as (count, value) pairs.
Step through it →A heap keeps its smallest item on top, and a push or pop only repairs one path from the top to a leaf, so each costs O(log n).
A push adds at the end and swaps up past larger parents. A pop moves the last item into the root's place and settles it along one path. Either way, only one path from the root to a leaf changes.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
Equal numbers count separately: the 4th largest is 4. Skipping repeats would give 3.
Count first, then keep the k most frequent as (count, value) pairs.
Step through it →Two heaps hold the smaller and the larger half. The median sits at their tops.
Step through it →Keep the end times of meetings in progress on a heap. The earliest end says whether a room is free.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
import heapqdef find_kth_largest(nums, k): if k > len(nums): return None heap = [] for x in nums: heapq.heappush(heap, x) if len(heap) > k: heapq.heappop(heap) return heap[0]