views:

25

answers:

1

Can a map and a min-heap used together give better amortized time that either on their own?

Let's suppose I have a project where I need to track several items. These items have an expiration time and a unique id:

class Item {
  ID uid;
  Time expiration;
};

For this example, both Time and ID are primitive integral data types. I need to be able to quickly access an item by id, and I also need to be able to find the minimum expiration of all items.

Additionally, I will make numerous insertions and deletions.

Using a map, I will get amortized look up times of O(log n). (Yes, I'll provide a compare function for that.) But finding the min value is O(n).

If I use a min-heap, my look up time by id will be O(n), but finding the min expiration is O(1).

In both cases, insertion are O(log n). For this program, deletions will only occur for the minimum item.

Or, I could use both. A map and a min-heap that track the same objects.

Given this set up, would it be beneficial to use both a min-heap and a map to avoid O(n) complexity?

+1  A: 

Yes, using double indexes will probably help you (given a sufficient number of items to defeat the constant factors involved). However, be careful - you'll want to keep track of where your item is in the min-heap so you can delete it from the heap quickly.

bdonlan
Thanks for your response. As a note, the only item I will remove is the top of the min-heap, so hopefully that is averted.
JoshD
Indeed, if you only ever remove the item that's at the top of the min-heap, it makes things simpler. Do keep an iterator to the position in the map as well though, to cut down on your constant factors for deletion.
bdonlan