Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why treemap takes O(log(n)) time in Get/put

Tags:

java

treemap

In one of the posts I saw that TreeMap takes O(log(n)) time for get/put. Can someone please answer why it takes O(log(n)), even when it can search directly through get/put using key?

like image 859
mac Avatar asked Oct 20 '14 05:10

mac


People also ask

What is the time complexity of a TreeMap?

TreeMap has complexity of O(logN) for insertion and lookup.

What is the time complexity of basic operations get () and put () in HashMap class?

Hashmap put and get operation time complexity is O(1) with assumption that key-value pairs are well distributed across the buckets.

Which is faster TreeMap or HashMap?

HashMap is a general purpose Map implementation. It provides a performance of O(1) , while TreeMap provides a performance of O(log(n)) to add, search, and remove items. Hence, HashMap is usually faster.

What is time complexity of Map in Java?

Key Points For operations like add, remove, containsKey, time complexity is O(log n where n is number of elements present in TreeMap. TreeMap always keeps the elements in a sorted(increasing) order, while the elements in a HashMap have no order.

Why is treemap so slow?

Performance wise TreeMap is slow if you will compare with HashMap and LinkedHashMap. The TreeMap provides guaranteed log (n) time complexity for the methods such as containsKey (), get (), put () and remove ().

What is the working of Treemap in Java?

Internal Working of TreeMap in Java. TreeMap class is like HashMap. TreeMap stores key-value pairs. The main difference is that TreeMap sorts the key in ascending order. TreeMap is sorted as the ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

Why is a treemap not thread safe?

The TreeMap provides guaranteed log (n) time complexity for the methods such as containsKey (), get (), put () and remove (). Also, a TreeMap is fail-fast in nature that means it is not synchronized and that is why is not thread-safe.

What is the worst-case time complexity of treemap?

The TreeMap itself is implemented using a red-black tree which is a self-balancing binary search tree. Since it uses a binary tree, the put (), contains () and remove () operations have a time complexity of O (log n). Furthermore, since the tree is balanced, the worst-case time complexity is also O (log n).


1 Answers

In a TreeMap, the key/value entries are stored in a Red-Black tree, and in order to find if a key is contained in the tree, you have to traverse it from the root, down some path, until reaching the required key or reaching a leaf.

A tree containing n elements has an O(log n) height, and therefore that's the time it would take to search for a key.

like image 193
Eran Avatar answered Nov 14 '22 23:11

Eran