← All problems

Kth Largest Element in a Stream

Easy heapsdesign LeetCode ↗
Design a class KthLargest that maintains the kth largest element in a data stream. The constructor takes (k, nums) with an initial array; add(val) appends val to the stream and returns the current kth largest element. Both initialization and each add call must be efficient for a long stream.

Hints (0/3 revealed)

Log in to reveal hints progressively.

Complexity

Time O(log k) per add, O(n log k) init; space O(k).

Common pitfalls

  • Using a max-heap, which cannot evict the smallest of the top-k efficiently.
  • Forgetting to trim the heap during initialization when len(nums) > k.
  • Returning the heap top before trimming back to size k.

Your solution

Log in to save your code and track progress.