Top K frequent number Concept Doubt

What I want to do is like:

Step 1: Make a node like

typedef pair<int,int>node;

where first one is number itself and other is its frequency till the numbers processed so far.

Step 2: Make min Heap for all the nodes. And min heap will form on the basis of number.

Step 3: When ever I insert new node then,

a. first, search it inside heap. Is it already present or not!

b. if present then find that node and increase its frequency by 1.

c. at the end, apply insertion() heap operation for that node by checking with its parent on the basis of frequency. And place it to the exact position.

But here’s my doubt, can I swap two nodes? Because I know, I can swap two numbers in general by using swap operation but swap two nodes which are pair of (number, frequency) itself; I don’t think so.

Hey @Kinjal

You have a good approach, but as you said that when it comes to swap two nodes which are a pair of (number, frequency) you have to keep this in mind that know your single node consist of three elements i.e., address of that node , number and it’s frequency of occurring which will occupy a space of o(3n) if you are planning to swap them. It will be a costly operation.
Hope this helped :grinning:

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.