Sub topic 3
Hash Tables: Average and Worst-Case Lookup
This chapter assumes you know arrays, the modulo operator, classes, and introductory Big-O notation.
Average and Worst-Case Cost
A hash table hashes a key, maps the hash to an array position, and checks the entry there. With a good hash function and a controlled load factor, only a few entries occupy each position. Lookup therefore takes constant time on average, written O(1).
The average case depends on the input distribution and table design. If many keys collide, a lookup may scan a chain or a probe sequence. In the worst case, every key can collide. Lookup then checks n entries and costs O(n).
Key Correctness
A key type must obey the equality and hash consistency rule: if two keys compare equal, they must produce the same hash. Equal keys can then find the same entry.
Keys should also be immutable while stored. If a key changes after insertion, its hash may point to a different position, making the entry difficult or impossible to find. Strings, numbers, and frozen records are common suitable keys.
Uses and Probing Variants
Hash tables implement dictionaries and sets. They also support counting frequencies, caching results, tracking visited items, and removing duplicates.
Open addressing stores entries directly in the array. Linear probing checks the next position after a collision. Quadratic probing checks offsets such as 1², 2², and 3², which can reduce long consecutive clusters. Double hashing uses a second hash function to choose the step size. These methods trade simpler storage for careful resizing and deletion rules.
Adversarial and Advanced Designs
Hash flooding occurs when an attacker chooses many keys that collide. Operations can degrade toward O(n), causing a denial-of-service risk. Libraries often randomize hash behavior per process or use keyed hashing, so attackers cannot easily predict collisions.
Robin Hood hashing moves entries so that items with short probe distances give space to items with longer distances. This can reduce variation in lookup time. Cuckoo hashing gives each key multiple possible positions and relocates existing entries when both are occupied. It offers predictable lookup, but insertion can trigger many relocations or a rebuild.
Standard Libraries
Standard libraries usually combine hashing, collision handling, resizing, and safeguards behind a dictionary or set interface. Exact designs differ. Some use chaining; others use open addressing or hybrid layouts. They may store cached hashes, compact entries, randomized seeds, and special rules for deletion. Use the library implementation unless you need a specialized memory, ordering, or concurrency guarantee.
Exercise
Why can a hash-table lookup be O(n) even when the table normally gives O(1) average lookup?
Show answer
Many keys can collide, forcing the lookup to scan a long chain or probe sequence.