Limited time: AI code review, hints, mock interviews, whiteboard analysis, and all Pro features are unlocked. Enroll

Kth Largest Element in a Stream

Easy

Topics
HeapDesignBinary Search Tree

Design a class to find the kth largest element in a stream (the kth largest in sorted order, not the kth distinct). Implement KthLargest(k, nums) which initializes with an integer k and a stream of integers nums, and add(val) which appends val and returns the kth largest element so far.

Example 1

Input:  operations = ["KthLargest","add","add","add","add","add"], values = [[3,[4,5,8,2]],[3],[5],[10],[9],[4]]
Output: [null,4,5,5,8,8]

Constraints

  • 1 <= k <= 10^4
  • At least k elements exist when add is queried.
  • At most 10^4 calls to add.
Run ⌘' · Submit ⌘⏎
SensAI SensAI
Beta
Listening...
Tap mic to stop voice mode

Unlock AI Features

One click to activate - no payment, no credit card. Just sign in and you're in.

AI code review and hints
SensAI chat assistant
AI mock interviews
Whiteboard analysis
100% free during early access