Practice

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 k and an initial array nums.
  • add(val) appends val to the stream and returns the kth largest element seen so far.

Examples

Example 1

InputKthLargest(3, [4,5,8,2]), add(3)Output4

Explanation. stream sorted desc: 8,5,4,3,2; 3rd largest is 4

Example 2

Inputadd(5)Output5

Explanation. 8,5,5,4,3,2; 3rd is 5

Example 3

Inputadd(10)Output5

Explanation. 10,8,5,5,4,3,2; 3rd is 5

Example 4

Inputadd(9)Output8

Explanation. 10,9,8,5,5,4,3,2; 3rd is 8

Example 5

Inputadd(4)Output8

Explanation. 10,9,8,5,5,4,4,3,2; 3rd is 8

Constraints

1 ≤ k ≤ 10⁴, up to 10⁴ add calls, 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)?