Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet look-up complexity?

A look-up operation OR contains for single can be O(n) in worst-case right ? So, for n elements look up in hashSet will be O(n^2)?

like image 960
phoenix Avatar asked Jul 04 '11 18:07

phoenix


People also ask

What's the lookup time for a HashSet?

On average, the contains() of HashSet runs in O(1) time. Getting the object's bucket location is a constant time operation. Taking into account possible collisions, the lookup time may rise to log(n) because the internal bucket structure is a TreeMap.

Why is a HashSet O 1?

Yes, accessing and finding an element in HashSet is O(1). HashSet stores elements using the hashing technique. Another important property of HashSet is that it contains only unique elements. For example you can check if the element already exists in HashSet.

What is the space complexity of HashSet in Java?

It's both: O(n+k).

Is HashSet faster than ArrayList?

Both Vector and HashSet Collection implementation classes performed poorly compared to the ArrayList Collection implementation class. Vector scored 68 TPS on average, while HashSet scored 9200 TPS on average. On the other hand the ArrayList outperformed Vector and HashSet by far, resulting in 421000 TPS on average.


2 Answers

Yes, but it's really the worst case: if all the elements in the HashSet have the same hash code (or a hash code leading to the same bucket). With a correctly written hashCode and a normally distributed key sample, a lookup is O(1).

like image 156
JB Nizet Avatar answered Sep 28 '22 11:09

JB Nizet


Yes, but the whole reason we have HashSets is that we encounter this worst case with very, very low probability, and it's usually much faster than the guaranteed nlogn for a heap or a (self-balancing) TreeSet, or the guaranteed n^2 for an unsorted list.

like image 39
krasnerocalypse Avatar answered Sep 28 '22 12:09

krasnerocalypse