Kth Largest Element in a Stream
Module 19 · Heaps
Problem
Design a class KthLargest that tracks the kth largest element in a
stream of numbers (note: the kth largest value in sorted order, counting
duplicates — not the kth distinct value).
- The constructor takes
kand an initial arraynums. add(val)appendsvalto the stream and returns the kth largest element seen so far.
Examples
Example 1
KthLargest(3, [4,5,8,2]), add(3)Output4Explanation. stream sorted desc: 8,5,4,3,2; 3rd largest is 4
Example 2
add(5)Output5Explanation. 8,5,5,4,3,2; 3rd is 5
Example 3
add(10)Output5Explanation. 10,8,5,5,4,3,2; 3rd is 5
Example 4
add(9)Output8Explanation. 10,9,8,5,5,4,3,2; 3rd is 8
Example 5
add(4)Output8Explanation. 10,9,8,5,5,4,4,3,2; 3rd is 8
Constraints
1 ≤ k ≤ 10⁴, up to 10⁴
addcalls, values in ±10⁴.
Attempt it first
The naive version is easy; the point is to find the version whose add
does not re-sort the whole stream each time. Before reading on, ask
yourself the sharp question: to answer "kth largest," how much of the
stream do you actually need to keep? You are never asked about the
elements smaller than the kth largest — can you throw them away? And of
the elements you keep, which single one is the answer, and where would it
sit in a heap so you can read it in O(1)?