Skip to content
Decoder

Kth Largest Element in a Stream

Easy

Problem

Build a class KthLargest that watches a stream of test scores and always knows the `k`th largest score so far. Duplicates count separately.

- KthLargest(k, nums) starts with k and an initial list of scores (possibly empty). - add(val) adds one score and returns the kth largest value in the stream after adding it.

Example 1

kl = KthLargest(3, [4, 5, 8, 2])

Example 2

Input
kl.add(3)
Output
4

Example 3

Input
kl.add(5)
Output
5

Example 4

Input
kl.add(10)
Output
5

Example 5

Input
kl.add(9)
Output
8

Example 6

Input
kl.add(4)
Output
8

Constraints

  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls to add.
  • Whenever add returns, the stream holds at least k values.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.