Kth Largest Element In a Stream
EasyNeetCode 150 Heap / Priority QueueTinderAdobeProblem
Build a class KthLargest that tracks the kth largest number in a growing
collection of integers. "kth largest" means the kth position when the numbers are sorted from big to small,
so duplicates count separately.
KthLargest(k, nums)starts with the numbers innums.add(val)insertsvaland returns the current kth largest number.
The input is a list of calls with their arguments; the output lists what each call returns
(null for the constructor).
Constraints
- 1 ≤ k ≤ 10⁴
- 0 ≤ nums.length ≤ 10⁴
- −10⁴ ≤ nums[i], val ≤ 10⁴
- add is only called when the collection holds at least k numbers afterwards
Examples: pick one to animate
Solutions
Time: Each add does one push and at most one pop on a heap of at most k + 1 items, and sifting walks at most log k levels. The constructor repeats that for every number in nums.
Space: The heap never keeps more than k numbers.
Keep only the k largest numbers in a min-heap. The smallest of those k numbers sits at the root, and that is exactly the kth largest overall. When a number arrives, push it; if the heap has grown past k, pop the root, because the smallest of k + 1 numbers can no longer be in the top k. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.