Not being able to solve

Please tell me where am I wrong

https://ide.codingblocks.com/s/325237 This is the updated code please check

in the code you have check only one condition

if(!elementPresent(pq,a[i]))
            {
                pq.push({a[i],0});
            }

what if it is present already
you have not consider that case
in priority queue you can’t update the value

also using priority queue time complexity will increase
because to print k elements through function you have to copy whole priority_queue
as it is passed by value hence take O(n) extra time

to solve this question you have to use map

Reference Code

But in the function call, I have updated its frequency the element is found

okay but your logic is not correct
first you are preparing the priority queue and then at end you are giving the ans
but in question it is said you have to print k most frequent element in running stream
means after each element you have to print tok k most frequent elements till now

1 Like

i have done some changes to your Code
it will give correct answer but the problem of time complexity is not resolved till now

to optimised it you have to use hashmap for this
see the reference code share in above reply

Your Modified Code

if you want to ask something about this feel free to ask
i hope this helps
if yes show your response with :heart: and don’t forgot to mark doubt as resolved

1 Like

Why did you change the comparator class operator? If the frequencies are same then elements should be stored in ascending order of the values, hence we should give them a.first<b.first

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.