Why is accessing an element of a dictionary by key O(1) even though the hash function may not be O(1)?

24,387

Solution 1

the HashFunc itself has a lot of operations behind the scenes

That is certainly true. However, the number of these operations depends on the size of the key, not on the size of the hash table into which the key is inserted: the number of operations to compute hash function is the same for a key in a table with ten or with ten thousand entries.

That is why the call of hash function is often considered O(1). This works fine for fixed-size keys (integral values and fixed-length strings). It also provides a decent approximation for variable-sized keys with a practical upper limit.

Generally, though, access time of a hash table is O(k), where k is the upper limit on the size of the hash key.

Solution 2

O(1) doesn't mean instant. O(1) means constant without regard to the size of the data. The hash function takes a certain amount of time, but that amount of time doesn't scale with the size of the collection.

Solution 3

It means that no matter what size your collection can be, it will still take almost the same amount of time to retrieve any of its members.

So in other words Dictionary with 5 members will let's say coud take around 0.002 ms to access one of them, as well as dictionary of 25 members should take something similar. Big O means algorithmic complexity over collection size instead of actual statements or functions executed

Solution 4

If a dictionary/map is implemented as a HashMap, it has a best case complexity of O(1), since i best case it requires exactly the calculation of the hash-code of the key element for retrieval, if there are no key collisions.

A hash-map may have a worst-case runtime complexity of O(n) if you have a lot of key collisions or a very bad hash function, since in this case it degrades to a linear scan of the entire array which holds the data.

Also, O(1) doesn't mean instantly, it means it has a constant amount. So choosing the right implementation for a dictionary may as well depend on the number of elements in the collection, since having a very high constant cost for the function will be much worse if there are only a few entries.

That's why dictionaryies/maps are implemented differently for different scenarios. For Java there are multiple different implementations, C++ uses red/black-trees, etc. You chose them based on the number of data and based on their best/average/worst-case runtime-efficiency.

Solution 5

Theoretically it is still O(n), because in the worst case all your data may end up having identical hash and be bundled together in which case you have to linearly go through all of it.

Share:
24,387
monogate
Author by

monogate

Updated on July 05, 2022

Comments

  • monogate
    monogate almost 2 years

    I see how you can access your collection by key. However, the hash function itself has a lot of operations behind the scenes, doesn't it?

    Assuming you have a nice hash function which is very efficient, it still may take many operations.

    Can this be explained?

  • klappvisor
    klappvisor almost 8 years
    But at the same time if your hash function is really bad, you may end up with a lot of values in the bucket, so O(1) won't hold anymore
  • acelent
    acelent almost 8 years
    It doesn't have to be that way, e.g. Java 8's HashMap resorts to a balanced tree in case it detects several collisions.
  • Martin C.
    Martin C. almost 8 years
    @acelent may be true, but then it is the classic hash-map any more. There are many different implementations for maps/dictionaries, fur exactly this case. I have amended the answer to point this out.
  • Kusalananda
    Kusalananda almost 8 years
    Constant amount of time, not linear.
  • Damian Yerrick
    Damian Yerrick almost 8 years
    Wouldn't a hash function need to contain more "if statements and multiple calculations" to produce a long enough hash value to uniquely identify 2 billion elements than it would for 200?
  • n0rd
    n0rd almost 8 years
    @klappvisor, not necessary that has function is bad. It may be that the input data is crafted. That's why O(1) here is amortized complexity, not the "true" complexity.
  • Owen
    Owen almost 8 years
    Also consider that it is impossible to have a hash table of n distinct items unless at least one item is represented by at least log(n) bits.
  • fluffy
    fluffy almost 8 years
    It doesn't mean that every member will take the same amount of time, it just (roughly) means that the upper bound on that access time does not grow with the size of the collection. Consider how a hash table handles disambiguating collisions. Similarly, looking up an item for a binary search tree is O(log2 n) because the worst case is log2 with the size of N, but an item near the root will take less time than a leaf item, for example.
  • Servy
    Servy almost 8 years
    But it is possible to write a hash function that is dependent on the size of the collection. It'd be stupid, and contrived, but you can do it. The statement that searching a hashset is actually premised on the assumption that computing the hash is O(1), which is virtually always, but not necessarily, the case.
  • Servy
    Servy almost 8 years
    @n0rd That's not actually what the "amortized" clarification of the O(1) means. The fact that it's an ammortized O(1) is to account for the fact that approximately 1/N of the additions (if you're adding to the set) will require reallocating a new backing array, which is an O(N) operation, so you can perform N additions in O(N) time, for an amortized O(1) addition, while a single addition is actually also O(N) (when not amortized). It's a separate clarification of the asymptotic complexity that it assumes the hashes are sufficiently well distributed.
  • Admin
    Admin almost 8 years
    @Servy Not even necessarily all that stupid and contrived. A custom list implementation that wants to allow two lists that hold equal items to compare as equal themselves may override GetHashCode() to combine the hash codes of the items in some way. If I were to implement such a class, for an initial implementation, I would implement GetHashCode() exactly like that. I would of course also change that later though.
  • Servy
    Servy almost 8 years
    @hvd That would be an O(m) hash, where m is the size of the inner collections. It still wouldn't be related to the size of the outer collection (the actual hash based structure). You'd need to have the items in the collection looking at all of the items of that same hash based collection that they are currently in for those items to have an O(n) (or any function of n) for their hash code. That would be pretty stupid and contrived.
  • Admin
    Admin almost 8 years
    @Servy Oh, that's what you meant. Yeah, that would be stupid. :) I can't come up with any remotely plausible scenario where you might want that.
  • Joker_vD
    Joker_vD almost 8 years
    Sadly, all operations are exponential if you don't restrict the inputs' bit size. But that's not a very interesting or useful result, right?
  • Tero Lahtinen
    Tero Lahtinen almost 8 years
    You do have a point, but when we talk about algorithmic complexity it does make sense to assume perfect hardware. The point is to define characteristics of an algorithm, not different real life hardware implementations. Besides, if you have big enough data, the complexity of the algorithm is really what matters most: is it e.g. O(1), (logN), O(n) or O(n^2).
  • vpalmu
    vpalmu almost 8 years
    @Owen: It is also not possible to have more items in an in-memory hashtable than can be unique assigned keys that fit in a pointer-sized variable.
  • Ed Avis
    Ed Avis almost 8 years
    There is also the issue of hash key collision with larger size dictionaries. Once you get big enough the majority of new entries will be colliding with an existing entry, causing a linear search through each hash bucket and ending up as O(n). Unless you make the hash keys grow longer as the size increases... but then you don't have O(1) either. I agree that in practice you may treat it as constant time but I would prefer to stay away from the formal O-notation for something that is only a rough approximation for small enough sizes, not a formal proof for any size.
  • Barmar
    Barmar almost 8 years
    @Servy The general point of hashing is to avoid O(n) search time, so creating a hash function that's O(n) would totally defeat the purpose. You could do it, but it would be like implementing addition recursively with Peano numbers: possible, but not really practical.
  • Eric J.
    Eric J. almost 8 years
    the number of these operations depends on the size of the key and on the size of the data being hashed.
  • Servy
    Servy almost 8 years
    @barmar sure, but while you are correct that it's a bad idea, it's possible, so you do need to consider it a possibility when you don't control the hash.
  • Barmar
    Barmar almost 8 years
    @Servy As far as I'm concerned, that would be like considering the possibility that array indexing is O(n). It could happen if arrays are implemented as linked lists, but I'm not going to worry about it.
  • Servy
    Servy almost 8 years
    @barmar but it's not possible for an array access to be O(N), and it is possible for a GetHashCode to have any arbitrary complexity, it's just preferable for it to be O(1).
  • Barmar
    Barmar almost 8 years
    @Servy GetHashCode() doesn't receive the hash table as a parameter, so how can it be dependent on the table size?
  • Servy
    Servy almost 8 years
    @barmar it's uncommon, but not unheard of, for an object to have a reference to its container. You could just explicitly pass it in if you wanted, but it could also come up through layers of indirection.
  • usr
    usr almost 8 years
    k does not need to be an upper bound. The lookup time is linear in the key size, so it's indeed O(k) where k is the key size. If k is understood as an upper bound then it's actually O(1).
  • Martin C.
    Martin C. about 7 years
    Please remember, that for a hash to be a valid key for a dictionary, it needs to be stable, i.e. not change after the object has been added to the dictionary. So it works only by hashing over some immutable part of the object. Otherwise you'll break the contract of most dictionary implementations. Also remember that at least for Java the contract is if a.equals(b) then hash(a)==hash(b). Having the collection as part of the hash-function will cause the whole dictionary to stop working, if this causes the hash to change if the collection changes.