A hash table stores key-value pairs by using a hashing function to calculate an array index for each key. It supports efficient insertion, search, and deletion, with average time complexity of , provided collisions and the load factor are managed effectively.
A hashing function converts a key into an integer index. For a table with slots, a simple calculation is:
For example, if and the table has slots, the key is stored at index . To retrieve the value, the same function is applied to the key, directing the algorithm to index .
A collision occurs when different keys produce the same index. Since collisions are unavoidable, the implementation must use a collision-resolution method.
| Method | How it resolves a collision |
|---|---|
| Separate chaining | Each index stores a collection, such as a linked list, containing all entries hashed to that index. |
| Open addressing | The algorithm searches for another empty slot within the table, using methods such as linear probing. |
The load factor measures how full the table is:
Here, is the number of stored entries and is the number of slots. For example, entries in slots give . As increases, collisions generally become more frequent. The table may therefore be and its entries into a larger array.
A common misconception is that hashing guarantees operations. This is only the average case; excessive collisions can produce worst-case time complexity of .
In an IB Computer Science response on B4.1 Fundamentals of ADTs, clearly trace the key through hashing, index calculation, collision resolution, and retrieval. If asked to explain efficiency, connect the load factor and collision frequency to average and worst-case performance.