Overview
A hash table is a data structure that stores data as key value pairs. It uses a hashing function to map each key to a position in memory which gives fast access when storing or retrieving values by that key.| Operations | Complexity |
|---|---|
| Access/Edit | O(1) |
| Insert | O(1) |
| Remove | O(1) |
Background
A hash table is built on three core components:- Key: The identifier used to access stored data.
- Hash Function: A process that turns the key into a numeric hash code.
- Buckets: An array in memory that holds the entries.
Hashing
The hash function converts
name into a number such as 417. This example uses character code sums. Real systems may use stronger functions for better distribution.Indexing
The table reduces that number to a valid index with a modulo step such as
417 % 10 which becomes 7. Again, real systems may use different indexing methods.name, the table repeats the hash and index calculations and retrieves the entry from bucket 7 immediately O(1).
Handling Collisions
A collision happens when two different keys map to the same bucket. Solution:- Chaining:
- Each bucket holds a small list of entries. If two keys map to bucket
7, both are stored in that list. - Lookups check bucket
7inO(1)time then scan the small list inO(n)time to find the matching key. - Keeping entries well distributed across buckets is important for performance because it keeps these lists short which reduces how often lookups fall back to
O(n)work.
- Each bucket holds a small list of entries. If two keys map to bucket