4

The average case time complexity for search in an unordered set in C++ O(1) but for worst case it is O(n). The same goes for insertion and deletion.

How does that work? The worst case time complexity for search should be when the element is not present in the map. If that takes O(n) time, it means that it tranverses the whole unordered set once. But if that's the case, shouldn't the average case complexity be O(n) as follows:

(1 + 2 + ... + n) / n = (n + 1) / 2

This means that there must be some other algorithm implemented to search. What's the algorithm?

  • Was just thinking about this the other day. Great question! –  Jul 27 '20 at 12:20
  • 2
    As per my knowledge, a basic implementation is, it creates a hash value, and then for every hash value, there will be a linked list attached. So every time you search for it only needs to search that specific linked list. But there will be some other functionality added to make it more robust. – Sai Sreenivas Jul 27 '20 at 12:22
  • 4
    This question is already answered here https://stackoverflow.com/questions/31112852/how-stdunordered-map-is-implemented – Anirudh Duggal Jul 27 '20 at 12:25
  • 1
    Consider a collection of baskets. You distribute eggs into the baskets according to some algorithm. Then one day, through some weird coincidence, all your eggs happen to be in the same basket. How many eggs do you need to examine in order to determine whether the egg you're looking for is there? – molbdnilo Jul 27 '20 at 12:29
  • I found this answer pretty simple to follow: https://stackoverflow.com/questions/24846798/is-the-complexity-of-unordered-setfind-predictable – Just another person Jul 27 '20 at 12:29
  • I was going to answer something like "We don't know, the spec only says what the step complexities are, it is up to the implementor how to achieve this", but I just looked it up, and much to my surprise, the spec actually very detailed specifies that they must be `HashSet`s and even explains how a `HashSet` works (as if someone writing an STL implementation wouldn't know that already). – Jörg W Mittag Jul 27 '20 at 12:46

0 Answers0