Click here to Skip to main content
15,892,674 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Design a class to efficiently find the Kth largest element in a stream of numbers. The class should have the following two things:​

The constructor of the class should accept an integer array containing initial numbers from the stream and an integer ‘K’.

The class should expose a function add(int num) which will store the given number and return the Kth largest number.

What I have tried:

i don't know how to solve this
Posted
Updated 12-Jan-22 4:03am
Comments
Richard Deeming 12-Jan-22 8:36am    
Your homework is set to test what YOU have learned, not how good you are at convincing a bunch of strangers to do your work for you.

If you really don't know where to start, talk to your teacher. That's what they're paid for!

Create an array of K elements, prefill it with the smallest number it can hold.
When you get a value, see if it is in the array already. If so, ignore it.
Check if it's lower that the lowest element in the array. If so, ignore it.
If not, insert it in the array in sorted order: between a lower and a higher value, or in the highest slot if necessary.
At the end of the stream, the lowest value in the array is the Kth highest value.
 
Share this answer
 
You need to understand that Homeworks are given for a reason. And the primary reason is to prepare you for real-world job tasks.

Apart from that, you don't even care to google the question, otherwise, you have had found the solution like below in less than a minute.

K'th largest element in a stream - GeeksforGeeks[^]

You have to understand that there is no shortcut of Success.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900