c++stringalgorithmdata-structureshash

Why do we say that finding a string in a hash table is O(1)?


Please, can someone explain this? What am I missing?

I tried asking ChatGPT, and also looked for solutions on the websites, but they were conflicting. ChatGPT says it will be O(L), but some websites say it will be O(1).


Solution

  • The C++ standard has this to say:

    [container.requirements.general]/2 All of the complexity requirements in this Clause are stated solely in terms of the number of operations on the contained objects. [Example: The copy constructor of type vector<vector<int>> has linear complexity, even though the complexity of copying each contained vector<int> is itself linear. —end example]

    Similarly, hash(string of length L) is treated as one operation on the contained object for purposes of discussing the complexity of operations on hash-based containers, even though actually computing the hash may take the amount of wall time proportional to L.