Data Structure for Ascending Order Key Value Pairs with Further Insertion

984 Views Asked by At

I am implementing a table in which each entry consists of two integers. The entries must be ordered in ascending order by key (according to the first integer of each set). All elements will be added to the table as the program is running and must be put in the appropriate slot. Time complexity is of utmost importance and I will only use the insert, remove, and iterate functions.

Which Java data structure is ideal for this implementation?

I was thinking LinkedHashMap, as it maps keys to values (each entry in my table is two values). It also provides O(1) insert/remove functionality. However, it is not sorted. If entries can be efficiently inserted in appropriate order as they come in, this is not a bad idea as the data structure would be sorted. But I have not read or thought of an efficient way to do this. (Maybe like a comparator)?

TreeMap has a time complexity of log(n) for both add and remove. It maintains sorted order and has an iterator. But can we do better than than log(n)?

LinkedList has O(1) add/remove. I could insert with a loop, but this seems inefficient as well.

It seems like TreeMap is the way to go. But I am not sure.

Any thoughts on the ideal data structure for this program are much appreciated. If I have missed an obvious answer, please let me know.

(It can be a data structure with a Set interface, as there will not be duplicates.)

2

There are 2 best solutions below

0
On

A key-value pair suggests for a Map. As you need key based ordering it narrows down to a SortedMap, in your case a TreeMap. As far as keeping sorting elements in a data structure, it can't get better than O(logn). Look no further.

0
On

The basic idea is that you need to insert the key at a proper place. For that your code needs to search for that "proper place". Now, for searching like that, you cannot perform better than a binary search, which is log(n), which is why I don't think you can perform an insert better than log(n).

Hence, again, a TreeMap would be that I would advise you to use.

Moreover, if the hash values, that you state, (specially because there are no duplicates) can be enumerated (as in integer number, serial numbers or so), you could try using statically allocated arrays for doing that. Then you might get a complexity of O(1) perhaps!