Kth Largest Element in a Stream - Heap - Easy - LeetCode
💻 coding

Kth Largest Element in a Stream - Heap - Easy - LeetCode

1 min read 244 words
1 min read
ShareWhatsAppPost on X
  • 1The KthLargest class is designed to find the kth largest element in a stream of numbers.
  • 2The constructor accepts an integer k and an initial integer array nums for the stream.
  • 3The add method returns the kth largest element after each new number is added to the stream.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The KthLargest class is designed to find the kth largest element in a stream of numbers."

Kth Largest Element in a Stream - Heap - Easy - LeetCode

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8 Note: You may assume that nums' length ≥ k-1 and k ≥ 1.

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:

int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums' length ≥ k-1 and k ≥ 1.

Time Complexity: O(nlogk)

Space Complexity: O(logk)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 4 October 2020 · 1 min read · 244 words

Part of AskGif Blog · coding

You might also like