Applied AI Engineer (LLM) coding learning path Level 2 This level · 16 of 31

Kth Largest Element in a Stream

Easy Heap

Problem

Design a class that is constructed with an integer k and an initial integer stream, and that supports adding a new value and returning the current kth largest element after each add.

Original: LeetCode 703: Kth Largest Element in a Stream.

Examples

Example 1

Input`KthLargest: KthLargest(3, [4, 5, 8, 2]), add(3), add(5), add(10), add(9), add(4)`
Output`[null, 4, 5, 5, 8, 8]`

Constraints

  • 0 <= nums.length <= 10^4
  • 1 <= k <= nums.length + 1
  • -10^4 <= nums[i] <= 10^4
  • -10^4 <= val <= 10^4
  • At most 10^4 calls will be made to add.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 703: Kth Largest Element in a Streamleetcode.com
  2. Java SE 17 API: PriorityQueuedocs.oracle.com
Previous
Next