Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computational Complexity of TreeSet methods in Java

Tags:

Is the computational complexity of TreeSet methods in Java, same as that of an AVLTree?

Specifically, I want to know the computational complexity of the following methods: 1.add 2.remove 3.first 4.last 5. floor 6. higher

Java Doc for method description: http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html

For an AVL Tree, there are all O(logn)? Whats the complexity of the above TreeSet Methods?

like image 638
user1628340 Avatar asked Jan 17 '13 12:01

user1628340


People also ask

What is the time complexity of TreeSet in Java?

For HashSet, LinkedHashSet, and EnumSet, the add(), remove() and contains() operations cost constant O(1) time thanks to the internal HashMap implementation. Likewise, the TreeSet has O(log(n)) time complexity for the operations listed in the previous group. This is because of the TreeMap implementation.

What is the time complexity of the following code snippet TreeSet?

From TreeSet : This implementation provides guaranteed log(n) time cost for the basic operations ( add , remove and contains ). You are performing a ~log(n) operation n times, hence the complexity is indeed O(n log(n)).

What sorting algorithm does TreeSet use?

The TreeSet class internally uses a TreeMap to store elements. The elements in a TreeSet are sorted according to their natural ordering. You may also provide a custom Comparator to the TreeSet at the time of creation to let it sort the elements based on the supplied comparator.


1 Answers

Operations which work on a single element are all O(ln n) comparisons except first and last which are O(1) comparisons or O(ln N) node search time.

comparator(), iterator(), clear(), first(), isEMpty(), size(), last(), pollFirst(), pollLast() are O(1)

add(), ceiling(), contains(), floor(), headSet(), higher(), lower(), remove(), subSet(), tailSet() are O(ln N)

clone(), equals(), hashCode(), toArray() and toString() are O(n)

like image 75
Peter Lawrey Avatar answered Sep 17 '22 14:09

Peter Lawrey