Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

136. Kth Largest Element in a Stream

EasyDay 41 of 60Heap / Priority Queue

Design a class KthLargest that tracks the kth largest value in a growing stream of numbers. The constructor KthLargest(k, nums) receives k and the initial numbers. Each call to add(val) inserts val and returns the current kth largest value of everything seen so far.

Example 1
Input: ["KthLargest","add","add","add","add","add"] [[3,[4,5,8,2]],[3],[5],[10],[9],[4]]
Output: [null,4,5,5,8,8]
After adding 3 the values are 2, 3, 4, 5, 8 and the 3rd largest is 4. Adding 5 makes it 5, and so on.
Constraints
  • 1 <= k <= 10^4
  • 0 <= nums.length <= 10^4
  • -10^4 <= nums[i], val <= 10^4
  • When add is called there are at least k values in total
Hints
Frequently asked at: Amazon, Meta, Adobe
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min