0

So i have a CUSTOM PriorityQueue(implemented using a max-heap) containing songs. Each song is an object that has a number of likes, the name of the song and a unique ID. The priority of each song inside the PriorityQueue is defined as the number of likes it has and if two songs have the same number of likes then the name of the song is compared.

I am asked to create a "remove" function that takes as an argument the ID of the song and removes it from the PriorityQueue. The problem is that i have to search for the song that has this particular ID in order to remove it which happens in O(n), since it is a linear search. I am supposed to make the remove function in O(logn) but from what i have read i understand it is impossible to search in an unsorted array in less than O(n)... can someone offer any ideas?

(the hint that we have is that we may have to add some things inside the getMax function (getMax returns the root of the PQ which contains the most popular song) and the insert function).

JDoe
  • 27
  • 7
  • In the insert function you can populate a hash table which maps IDs to their corresponding songs. You can then look up a song in `O(1)` and remove it from the max-heap in `O(log N)`. – meowgoesthedog Dec 11 '18 at 14:12
  • @meowgoesthedog It's more involved than just adding an entry in a hash table during insertion. You have to maintain that hash table, updating the indexes whenever any item is moved in the heap. So whenever items are swapped during an insertion and deletion, their corresponding entries in the hash table have to be updated. – Jim Mischel Dec 11 '18 at 15:45
  • What you're looking for is called an indexed priority queue. Java doesn't have one built in. See https://stackoverflow.com/questions/10346525/does-java-have-an-indexed-minimum-priority-queue – Jim Mischel Dec 11 '18 at 15:46
  • @JimMischel could use object references in both structures instead? This would not be affected by hashtable or heap operations. – meowgoesthedog Dec 11 '18 at 15:46
  • @meowgoesthedog If your priority queue implementation uses nodes with right, left, and parent references, yes. But typical binary heap priority queues are implemented in arrays. The array structure imposes the parent/child relationships implicitly. The references move around in the array. If you want to use object references in the hash table, then the object would have to know its position in the array. The only way to do that would be to have an `index` field in the object, which is updated during insertion and deletion. Again, you have to modify the PQ code to support this. – Jim Mischel Dec 11 '18 at 15:50
  • @JimMischel OP's description strongly suggests that the PQ/max-heap implementation in question already supports custom comparison operators, so a re-implementation of the PQ *itself* is unlikely to be necessary. – meowgoesthedog Dec 11 '18 at 15:54

0 Answers0