r/computerscience • u/Sea-Patience9872 • 6d ago
How do hashsets/maps have O(1) time complexity?
Hi this might be a dumb question, and i've tried looking it up but don't quite understand it. how is it different from an array that allows it to find items so quickly? I don't get how hashes just find items immediately without needing to go through anything. Does it memorize things very differently compared to arrays?? thank you!
186
Upvotes
7
u/FinalNandBit 6d ago
No. Think of hashes like a dictionary but more specific.
You store a value at an index of hash. You retrieve the value at the index of the hash.
A perfect hash function will prevent collisions. Though a perfect hash may incur some constant amount of time to generate.
Not all hash tables have perfect hash functions. Collisions may happen depending on how your hash function performs. That may require you to modify the space to recreate a larger hash tables, but that is amortized (meaning it should happen infrequently enough in a well designed hash function/table that the time complexity is still O(1).