Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of set in Java

Can someone tell me the time complexity of the below code?

a is an array of int.

Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
    if (set.contains(arr[i])) {
        System.out.println("Hello");
    }
    set.add(arr[i]);
}

I think that it is O(n), but I'm not sure since it is using Set and this contains methods as well. It is also calling the add method of set.

Can anyone confirm and explain what the time complexity of the entire above code is? Also, how much space would it take?

like image 718
Mike Avatar asked Jul 20 '11 22:07

Mike


People also ask

What is the time complexity of a set?

Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal). The time complexity of set operations is O(log n) while for unordered_set, it is O(1).

What is the time complexity of set in Java?

the elements in a set are sorted, but the add, remove, and contains methods has time complexity of o(log (n)).

Which is faster List or set in Java?

Core Java bootcamp program with Hands on practice The array is faster in case of access to an element while List is faster in case of adding/deleting an element from the collection.

What is the time complexity of TreeSet in Java?

Likewise, the TreeSet has O(log(n)) time complexity for the operations listed in the previous group. This is because of the TreeMap implementation. The time complexity for ConcurrentSkipListSet is also O(log(n)) time, as it's based in skip list data structure.


1 Answers

i believe its O(n) because you loop over the array, and contains and add should be constant time because its a hash based set. If it were not hash based and required iteration over the entire set to do lookups, the upper bound would be n^2.

Integers are immutable, so the space complexity would be 2n, which I believe simplifies to just n, since constants don't matter.

If you had objects in the array and set, then you would have 2n references and n objects, so you are at 3n, which is still linear (times a constant) space constraints.

EDIT-- yep "This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets."

see here.

like image 158
hvgotcodes Avatar answered Oct 12 '22 16:10

hvgotcodes