Hashing and Hash Tables
Hashing and Hash Tables
Hashing is a technique that allows a program to locate data quickly by transforming a key into an index. Instead of searching through every stored item one at a time, a program can calculate where the desired item should be located and go directly there.
Imagine a library containing one million books arranged randomly. If the books are stored without an organizing system, finding one particular book may require checking hundreds of thousands of books. This is a linear search: items are examined one by one until the desired item is found. As the number of books increases, the amount of searching usually increases as well.
Hashing provides a different strategy. If a book’s title can be converted into a position in the library, the program can calculate that position immediately. The search no longer depends directly on checking every earlier book.
The Basic Idea of Hashing
Hashing is the process of converting a key into a fixed-size value. The produced value is called a hash or hash value.
For example, the key might be the string "inside code". A hash function could convert that string into the number 29.
Hashing converts a key into a value that can be used to locate associated data.
The key is the information used to identify an item. In different applications, a key could be:
- A book title
- A person’s name
- A word
- An identification number
- A username
- A tuple of values
The hash value is not usually the data itself. Instead, it is used to determine where the associated data should be stored.
Why Hashing Is Useful
Suppose a library has 1,000,000 positions, numbered from 0 through 999,999. If a book title is hashed to position 472,819, the book should be stored at that position. Later, the same title can be hashed again, producing the same position, and the program can immediately inspect that location.
This gives the key a predictable route to its associated value:
- Start with the key.
- Apply the hash function.
- Receive an index.
- Go directly to that index.
- Retrieve the associated value.
The process only works if insertion and searching follow the same rule. When a book is inserted, it must be placed at the position calculated from its title. Otherwise, calculating the title’s position later would not lead to the book.
Think About It
If a key were inserted at a random position instead of the position produced by its hash function, what would happen when the program later calculated the key’s hash?
Hash Tables
A hash table is a data structure that stores key/value pairs. It uses hashing to determine where each value belongs.
A hash table can be viewed as an array of slots:
- The key identifies an item.
- The value is the information associated with that key.
- The hash function converts the key into an index.
- The slot at that index stores the key/value pair or a structure containing it.
In the library analogy:
| Hash-table concept | Library analogy |
|---|---|
| Key | Book title |
| Value | Book itself |
| Array of slots | Library |
| Index | Position in the library |
For a phone agenda, the person’s name might be the key and the phone number the value. For a dictionary, a word might be the key and its definition the value.
The hash table does not search the entire collection for a value. It uses the key to calculate the location where the value should be found.
Hash Functions
A hash function is a function that accepts a key, performs computations on it, and returns a hash value. When a hash table has m slots, the hash function must produce a valid index from 0 through m−1.
A hash function can be represented conceptually as:
h(key)=indexThere is no single universal hash function. Different applications can use different hash functions, and programmers can design their own.
A Simple String Hash Function
One simple approach for strings is:
- Convert every character to its ASCII code.
- Add all the ASCII codes together.
- Calculate the result modulo m.
The modulo operation produces a remainder in the range from 0 through m−1.
For the key "inside code", suppose the sum of the ASCII codes is 1079 and the table has m=30 slots. The hash is:
Therefore, this hash function assigns "inside code" to index 29.
The number 29 is not the string itself. It is the calculated location of the value associated with that string.
Determinism
A hash function must be deterministic. This means that the same key must always produce the same hash value.
For a key k:
h(k)=the same result every timeThis requirement is essential. If a key produced one index during insertion and a different index during searching, the program would look in the wrong location and fail to find the value.
Properties of a Useful Hash Function
A useful hash function should generally have two important properties:
- It should distribute keys as evenly as possible among the available indices.
- It should be computationally efficient.
A function that takes too long to calculate would reduce the benefit of using a hash table. A function that sends too many keys to the same index would create many collisions and make searching slower.
Common Applications of Hash Tables
Hash tables are appropriate when data consists of keys and associated values.
Phone Agendas
A phone agenda can store:
- Key: a person’s name
- Value: the person’s phone number
To find a phone number, the person’s name is hashed. The resulting index identifies the location containing the number.
Word Counters
A word counter records how many times each word appears in a text:
- Key: a word
- Value: the number of occurrences
When a word is encountered, the program checks whether its key already exists. If it does, the associated count can be increased. If not, a new key/value pair can be inserted with an initial count.
Dictionaries
A dictionary can store:
- Key: a word
- Value: its definition
Hashing the word gives the location of its definition.
These examples share the same pattern: an identifiable key is associated with a value, and the key can be used to retrieve that value efficiently.
Collisions
A collision occurs when two different keys produce the same hash value and therefore the same index.
For example, suppose a phone agenda uses a table with 30 slots:
"Samy Sterious"hashes to index 14."Khaled Anas"also hashes to index 14.
The two names are different, but the hash function assigns both to the same location. The values cannot simply occupy the exact same single-value slot, so the hash table needs a collision-handling strategy.
Collisions are unavoidable in many situations because a hash table usually has a finite number of possible indices, while the number of possible keys can be much larger.
Why Keys Must Be Stored Alongside Values
When a collision occurs, the hash value only identifies a location, not necessarily one unique key. If a slot contains values associated with several keys, the program must determine which value belongs to the requested key.
Therefore, a collision-handling structure stores each complete key/value pair, not just the value.
For example, a phone agenda must store both:
"Khaled Anas"and the phone number"Samy Sterious"and the phone number
When searching for "Khaled Anas", the program hashes the name to index 14, then compares the requested name with the stored keys at that location.
Think About It
Why would storing only phone numbers at a collision-prone index make it impossible to identify the correct person’s number?
Separate Chaining
Separate chaining handles collisions by allowing each table slot to contain a linked list of key/value pairs.
Instead of each slot holding only one value, each slot holds the beginning of a list. Every key whose hash equals that slot’s index is added to the list.
If three keys hash to index 13, the slot at index 13 contains a linked list with three nodes:
slot 13⟶node1⟶node2⟶node3Each node stores:
- A key
- Its associated value
- A pointer to the next node
For the phone agenda example, both "Samy Sterious" and "Khaled Anas" can be stored in the linked list at index 14.
Searching with Separate Chaining
To find a value:
- Hash the requested key.
- Go to the linked list at the resulting index.
- Traverse the list.
- Compare the requested key with the key in each node.
- Return the value from the matching node.
The list is necessary because the hash only identifies the possible location. The key comparison identifies the exact item.
Inserting with Separate Chaining
When inserting a key/value pair:
- Calculate the key’s index.
- Search the linked list at that index.
- If the key already exists, update its value.
- If the key does not exist, add a new node to the list.
A common implementation inserts a new node at the beginning of the linked list. This takes constant time because the program does not need to traverse the existing nodes.
Open Addressing
Open addressing handles collisions without linked lists. Each table slot contains at most one key/value pair. When the desired slot is occupied, the algorithm searches for another available slot. This search process is called probing.
Linear Probing
One form of open addressing is linear probing. When a collision occurs, the program checks the next slot, then the next one, continuing until it finds an empty location.
For example:
- The key hashes to index 14.
- Index 14 is occupied.
- Check index 15.
- Index 15 is occupied.
- Check index 16.
- Index 16 is occupied.
- Check index 17.
- Index 17 is empty, so insert the pair at index 17.
The key must still be stored with the value. During a search, the program may need to inspect several positions and compare stored keys to the requested key.
Comparing the Two Collision Strategies
| Strategy | How collisions are handled |
|---|---|
| Separate chaining | A slot contains a linked list of key/value pairs |
| Open addressing | The algorithm probes alternative slots |
| Linear probing | Alternative slots are checked sequentially |
Neither strategy eliminates the underlying issue of collisions. They provide ways to continue storing and finding data when collisions occur.
Why Collisions Cannot Usually Be Avoided
A hash table with m slots has only m possible hash values. However, the set of possible keys may be unlimited. There are infinitely many possible strings, for example.
The Pigeonhole principle states that if more items are placed into fewer available locations, at least two items must share a location. Therefore, if more than m different keys are inserted into a table with m slots, a collision must occur.
Even when the number of keys is less than or equal to the number of slots, a particular hash function may still map two keys to the same index.
Perfect Hashing
A perfect hash function maps a known collection of keys to distinct table positions, with no collisions.
For example, if there are 20 known keys and 30 slots, it may be possible to design a hash function that maps each key to a different slot. This works especially when:
- The set of keys is known in advance.
- No additional keys will be inserted.
- The table has enough slots for the known keys.
Perfect hashing is not always practical because many applications receive new keys continuously or work with an extremely large set of possible keys.
Distribution and Hash-Function Quality
A hash function should distribute keys evenly across the available indices.
Suppose a table has 30 indices, but a hash function sends most keys to indices 0 through 4. Those five locations will accumulate many collisions, while most of the table remains unused.
A better hash function gives each possible index roughly the same probability of receiving a key. This spreads the keys throughout the table and keeps collision-handling structures smaller.
A poor hash function tends to:
- Concentrate keys in a small range of indices
- Produce many collisions
- Leave other slots unused
- Increase search time
A better hash function tends to:
- Spread keys broadly across the table
- Reduce the number of collisions
- Keep linked lists short in separate chaining
- Reduce probing sequences in open addressing
Rehashing
Even a good hash function cannot compensate for a table that is too small.
Suppose a hash table has 10 slots and must store 50 keys. On average, each slot would correspond to:
1050=5keys. This creates substantial collision pressure, regardless of how evenly the hash function distributes the keys.
Rehashing addresses this problem by creating a larger table and inserting all existing key/value pairs into it again.
A typical rehashing process is:
- Save the old table.
- Increase the capacity, often by doubling it.
- Create a new, empty table.
- Reset the size of the table.
- Recalculate the index of every old key using the new capacity.
- Insert every key/value pair into the new table.
The keys must be hashed again because changing the table capacity changes the modulo calculation and therefore may change each key’s index.
Rehashing reduces collisions by distributing the keys over a larger range of possible indices.
Why Rehashing Can Fail with a Poor Hash Function
Consider the simple hash function based on the sum of ASCII codes. Suppose keys are strings containing at most 20 alphabetical characters, and the largest ASCII code is 122. The maximum possible character-code sum is:
20×122=2440Therefore, this hash function cannot produce values greater than 2440 in that situation.
If a table has 2500 slots, the indices after 2440 can never be reached by this hash function. Those slots remain useless. Increasing the table size does not distribute keys into those unreachable positions, so rehashing may fail to reduce collisions meaningfully.
A good hash function must use the table capacity effectively rather than restricting all keys to a small portion of the table.
Load Factor
The load factor measures how full a hash table is. It is based on the ratio:
mnwhere:
- n is the number of stored elements
- m is the number of slots
For example, if n=21 and m=30:
mn=3021=0.7The load factor threshold is the maximum permitted value of this ratio before rehashing occurs.
If the threshold is 0.75, rehashing occurs when the table’s ratio exceeds 0.75. For a table with 100 slots:
- The first 75 elements do not exceed the threshold.
- Inserting the 76th element causes the ratio to exceed 0.75.
- The table then rehashes into a larger table.
Load Factor in Open Addressing
In open addressing, each slot can hold at most one element. Therefore:
n≤mThe ratio mn must be between 0 and 1:
- 0 means the table is empty.
- 1 means every slot is occupied.
Load Factor in Separate Chaining
In separate chaining, one slot can contain many elements in its linked list. Therefore, n can be greater than m.
For example, if 50 elements are stored in 20 slots:
mn=2050=2.5The load factor can therefore exceed 1 in a separately chained table.
Time-and-Space Tradeoff
A lower load factor means more slots relative to stored elements. This usually reduces collisions and improves time efficiency, but it uses more memory.
A higher load factor means fewer slots relative to stored elements. This saves memory but increases collisions and can make operations slower.
The load factor is therefore a tradeoff:
| Lower load factor | Higher load factor |
|---|---|
| Fewer collisions | More collisions |
| Faster average operations | Slower average operations |
| More unused space | Less unused space |
| Greater memory usage | Lower memory usage |
A threshold of 0.75 is often a useful default, but the best choice depends on whether time efficiency or space efficiency is more important.
Think About It
Why can doubling the number of slots improve performance even though every existing element must be moved during rehashing?
A Simple Hash Table Implementation
A separately chained hash table can be built from three main structures:
- Nodes
- Linked lists
- The hash table itself
Nodes
A node represents one stored key/value pair. It contains:
- The key
- The value
- A pointer to the next node
The pointer allows multiple nodes to form a linked list inside one table slot.
Linked Lists
Each slot contains one linked list. The linked list needs operations such as:
- Insert: Create a new node and place it at the beginning.
- Search: Traverse the nodes until the requested key is found.
- Delete: Find the node containing the requested key and remove it by adjusting pointers.
Inserting at the beginning is efficient because the new node points to the current head, and the new node becomes the new head.
Searching and deleting require traversal because the target node may appear anywhere in the list.
Hash-Table Components
A hash table generally stores:
- Capacity: The number of slots, initially perhaps 30.
- Size: The number of stored key/value pairs, initially 0.
- Load factor threshold: For example, 0.75.
- Array of slots: Each slot contains a linked list.
Typical hash-table methods include:
- Hashing a key
- Rehashing the table
- Inserting or updating a key/value pair
- Checking whether a key exists
- Retrieving a key’s value
- Deleting a key/value pair
Insertion and Updating
An insertion operation follows this process:
- Hash the key to calculate its index.
- Access the linked list at that index.
- Search the list for the key.
- If the key exists, replace its old value with the new value.
- If the key does not exist, insert a new node.
- Increase the table size if a new node was added.
- Check the load factor.
- Rehash if the threshold has been exceeded.
The distinction between updating and inserting is important because keys are unique. Inserting the same key again should not create a duplicate key; it should update the existing value.
Searching for a Key
To check whether a key exists:
- Hash the key.
- Go to the linked list at the resulting index.
- Search the list.
- Return true if a matching node is found.
- Return false otherwise.
Retrieving a Value
To retrieve a value:
- Hash the key.
- Go to the corresponding linked list.
- Search for the matching key.
- Return its value if found.
- Return a null-like result if the key does not exist.
Deleting a Key/Value Pair
To delete a pair:
- Hash the key.
- Go to the linked list at the calculated index.
- Search for the matching node.
- Remove it if found.
- Decrease the table size if deletion succeeds.
A hash table may also support shrinking. If the table becomes too empty, it can rehash into a smaller table to reduce wasted space.
Time Complexity
Time complexity describes how the running time of an operation changes as the amount of stored data increases.
Linked-List Operations
Inserting at the beginning of a linked list takes constant time:
O(1)The operation does not depend on the number of existing nodes.
Searching for a node requires traversing the list. If the list has length l, the search takes:
O(l)Deleting a node also requires searching for it, so deletion takes:
O(l)Hashing Time
The hash function is considered to take:
O(1)with respect to the number of elements in the hash table because it does not traverse the table’s stored elements.
Strictly speaking, processing a long key can depend on the key’s size. However, hashing may still be treated as constant time when:
- Keys have a fixed-size representation, such as common integer types.
- The hash function examines only a fixed number of characters.
- The maximum key size is bounded by a fixed limit.
The important point is that the hash function’s running time does not grow with the number of elements already stored in the table.
Best and Worst Cases for Collisions
With separate chaining:
- In the best case, there are no collisions, and each list has length 0 or 1.
- In the worst case, every key hashes to the same index, creating one list of length n.
The corresponding search costs are:
O(1)in the best case, and
O(n)in the worst case.
A good hash function and appropriate rehashing make the worst case less likely, although they cannot mathematically eliminate it for arbitrary inputs.
Average Case
In a well-designed hash table, collisions are distributed among many slots, so the linked lists remain short on average. The search through a list can then be treated as constant time on average:
O(1)This produces average-case constant-time operations for searching, retrieving, and deleting.
Amortized Complexity of Insertion
Insertion has an additional complication: rehashing.
Most insertions involve:
- Computing a hash
- Searching a short list
- Inserting at the beginning of a list
These steps take O(1) time on average.
Occasionally, an insertion causes the load factor to exceed its threshold. Rehashing then requires visiting and reinserting all existing elements, which takes:
O(n)for that particular operation.
However, rehashing happens infrequently. After the table grows, many future insertions can occur before another rehash is necessary. When the total cost of all insertions is averaged over a large sequence of operations, the cost per insertion remains:
O(1)This is called amortized complexity. An occasional expensive operation is balanced by many inexpensive operations.
Average Complexities of Main Operations
For a well-implemented hash table:
| Operation | Average complexity |
|---|---|
| Insert or update | O(1) amortized |
| Search for a key | O(1) |
| Get a value | O(1) |
| Delete | O(1) |
The worst-case complexity of these operations can still be:
O(n)if many keys collide and one structure becomes very long.
Space Complexity
Space complexity describes how much memory a data structure uses as the number of stored elements increases.
A hash table’s memory comes mainly from:
- The nodes representing stored elements
- The array of slots
There are n nodes, one for each stored element. The number of slots is generally proportional to n, determined by the selected load factor. If the number of slots is c times the number of elements for some constant c, the total space remains linear:
O(n)Thus, a hash table has O(n) space complexity.
The Two Sum Problem
Hash tables can improve the time complexity of common algorithmic problems.
In the two sum problem, an array contains numbers, and the goal is to find two elements whose sum equals a target value k. The desired result is often the indices of those two elements.
A slow approach checks every pair:
- Compare the first element with every later element.
- Compare the second element with every later element.
- Continue until a valid pair is found.
This takes:
O(n2)time because the number of possible pairs grows quadratically.
A hash-table approach works differently. As the array is scanned, the algorithm stores each number and its index. For a current element x, the needed companion is:
k−xThe algorithm checks whether k−x has already been stored:
- Read the current element x.
- Calculate k−x.
- Look up k−x in the hash table.
- If it exists, return the previous index and the current index.
- Otherwise, store x and its index.
- Continue scanning.
Because each lookup and insertion takes O(1) on average, the entire algorithm takes:
O(n)time, improving substantially over O(n2).
Requirements for Keys and Values
Hash tables treat keys and values differently.
Keys Must Be Unique
A hash table should not contain the same key twice. If the same key is inserted again, the usual behavior is to update its existing value.
For example, a phone agenda should have one entry for a person’s name rather than multiple indistinguishable entries for the same key.
Values do not need to be unique. Different keys can refer to the same value without causing a problem.
For example:
- Two people may share a phone number.
- Two words may have the same definition.
- Two keys may both map to the number 0.
Keys Must Be Immutable
A key must also be immutable, meaning that its relevant contents cannot change after it is used in the hash table.
Suppose an array is used as a key. Before modification, the array may produce hash value 56. If an element is added later, the array’s contents change. Hashing the modified array may produce a different result.
The hash table originally placed the value using the old hash, but a later search could calculate the new hash and look in a different location. The value would effectively become lost.
Suitable immutable key types can include:
- Integers
- Strings
- Tuples, when their contents are also appropriately immutable
Mutable types that generally should not be used as keys include:
- Arrays
- Sets
- Other objects whose hash-relevant contents can change
Values do not have this restriction. A value is not used to calculate the storage location, so it can be mutable. A value may be an integer, string, array, set, object, or even another hash table.
A hash-table key must be unique and stable; a value may be repeated and may be mutable.
Other Uses of Hashing
Although this lesson focuses on hash tables, hashing has additional applications, including cryptography. In those contexts, hashing is used for purposes beyond locating values in an array, but the central idea remains the transformation of input data into a fixed-size result.
Programming languages often provide built-in hash-table implementations. Examples include:
- Python’s
dict - Java’s
HashMap - C++’s
unordered_map
These built-in structures handle many implementation details, while understanding nodes, collisions, load factors, and rehashing explains how the underlying idea works.
Comprehensive Review
Hashing converts a key into a fixed-size hash value. A hash function performs this conversion and must be deterministic, so the same key always produces the same result. A hash table uses the resulting hash as an index into an array of slots to store and retrieve key/value pairs efficiently.
Because many possible keys must often share a limited number of slots, collisions are unavoidable in general. Separate chaining stores colliding pairs in a linked list, while open addressing searches for alternative slots through probing. Linear probing checks subsequent slots one at a time.
A good hash function distributes keys evenly and calculates results efficiently. A table that becomes too full can rehash by creating a larger table and inserting all elements again. The load factor, mn, determines when rehashing occurs and balances time efficiency against memory efficiency.
With a good implementation, insertion is O(1) amortized, and searching, retrieving, and deleting are O(1) on average. The worst case remains O(n) when collisions are heavily concentrated. The total space complexity is O(n).
Keys must be unique and immutable because their hashes determine their locations. Values may be duplicated or mutable because they are retrieved from the locations determined by keys. Hash tables are therefore especially useful whenever a program must repeatedly associate identifiable keys with values, such as phone numbers, word counts, dictionary definitions, or previously seen elements in the two sum problem.

Ask anything
We've read this whole study set, so questions about it get the best answers.