24 · Heaps & Priority Queues

#703 Kth Largest Element in a Stream

Easysolve on LeetCode ↗

frequently reported atAdobeAmazonMetaGoogleMicrosoftGoldman Sachs

the problem

In plain words

Design KthLargest(k, nums) with add(val) that inserts val into the stream and returns the kth largest value seen so far.

in k = 3, nums = [4,5,8,2]; add(3), add(5), add(10), add(9), add(4)

out 4, 5, 5, 8, 8

in k = 4, nums = [7,7,7,7,8,3]; add(2), add(10), add(9), add(9)

out 7, 7, 7, 8

Equal values count separately: the top four after add(10) are 10, 8, 7, 7.

  • 0 ≤ nums.length ≤ 10⁴
  • 1 ≤ k ≤ nums.length + 1
  • -10⁴ ≤ nums[i], val ≤ 10⁴
  • At most 10⁴ calls to add

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #215
    2. #295