Kth Largest Element in a Stream
Try to solve the Kth Largest Element in a Stream problem.
We'll cover the following
Statement#
Given an infinite stream of integers (sorted or unsorted), nums, design a class to find the largest element in a stream.
Note: It is the largest element in the sorted order, not the distinct element.
The class should have the following functions, inputs, and return values:
-
Init(nums, k): It takes an array of integers
numsand an integerkand initializes the class object. -
Add(value): It takes one integer
value, appends it to the stream, and returns the element representing the largest element in the stream.
Constraints:
-
nums.length -
nums[i] -
value - At most, calls will be made to add.
- It is guaranteed that there will be at least elements in the array when you search for the element.
Examples#
1 of 5
2 of 5
3 of 5
4 of 5
5 of 5
Understand the problem#
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Largest Element in an Array
Given the following inputs, what will be the output?
nums = [4, 2, 1, 3, 5, 8]
k = 5
9
2
8
5
Figure it out!#
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself#
Implement your solution in the following coding playground:
Top K Elements: Introduction
Solution: Kth Largest Element in a Stream