3

I currently have data that I need sorted in two different ways, from a time and space complexity PoV, is there any alternative to maintaining two trees, one sorted by date and one by ID number? I need to be able to return lists in order of data, and individual users by ID, and I would prefer not to have to traverse or even worse, traverse and then sort for the array returns.

Any insight or help is much appreciated, thanks!

Harrison W.
  • 197
  • 11

2 Answers2

2

You could do that in one tree, but you would get O(logN) performance only for the date. The ID direct retrieval would be O(N) (i.e. traversing the whole tree to find an exact match) anyway, since the order would be indetermined.

If your ID could be based on the date you need (I mean if the ID could be generated basing on the date) - then you could reduce the O(N) time-complexity to O(logN + M), where M - is a subset of ID's for a particular date.

So depending on your response time and memory requirements, you could keep just one tree, or pair it with a HashMap of ID's.

bashnesnos
  • 816
  • 6
  • 16
  • Thanks for the response, I am given ids and dates which are out of my control and unordered annoyingly, that would be a good idea to generate based on date otherwise. I think I will just stick with two trees as the memory uncertainty is a factor for making a hashmap, it is likely I'd have to resize a few times, and time isn't too much better with one. – Harrison W. Mar 01 '17 at 12:53
  • 1
    @HarrisonW. you're welcome :-) I would still recommend you to use a tree and and a hashmap, since even insertion + resizing the hashmap several times would outperform insertion into a balanced tree. – bashnesnos Mar 01 '17 at 13:03
1

TreeMap implements Red-Black tree which is an alternative to AVL.

Kiryl
  • 111
  • 4