Hashing and Hash Tables
Hashing and Hash Tables
Hashing: The Core Idea
Hashing is the process of converting a key into a fixed-size numerical value called a hash. The hash is used to determine where the data associated with that key should be stored.
For example:
Key:
"inside code"Hash: 29
The hash does not usually contain the original key or value. Instead, it acts as an index that helps locate the associated value quickly.
Linear Search Versus Hashing
Suppose a library contains one million randomly arranged books.
With linear search, a search begins at the first book and checks books one by one until it finds the target. The more books the library contains, the longer the search may take.
Hashing provides a different approach:
The book title is used as the key.
A hash function converts the title into a number.
That number identifies the book’s position in the library.
The search goes directly to the calculated position instead of checking every previous book.
This makes hash-based lookup much faster on average.
Hashing provides a way to convert a key into a location so that associated data can be accessed efficiently.
The lookup works correctly only if insertion follows the same rule. When a book is inserted, it must be placed at the position calculated from its title. Later, searching for that title will produce the same position.
Hash Tables
A hash table is a data structure that stores key/value pairs.
A key identifies the data.
A value is the data associated with that key.
An array provides a collection of storage locations called slots or buckets.
A hash function converts the key into the index of the slot where the value should be stored.
Library Analogy
In the library example:
Key: The title of a book
Value: The book itself
Array: The library
Index: The book’s position in the library
If the library has m slots, valid array indices range from 0 through m−1.
For a phone agenda:
Key: A person’s name
Value: The person’s phone number
For a dictionary:
Key: A word
Value: The word’s definition
The key/value relationship is the central reason to use a hash table.
Hash Functions
A hash function is a function that:
Accepts a key as input.
Performs computations on that key.
Returns a hash value, usually corresponding to an array index.
For a hash table containing m slots, the hash function should produce a value in the range:
where h(k) is the hash of key k.
A Simple Hash Function for Strings
One basic string hash function can be created by:
Converting every character to its ASCII code.
Adding the ASCII codes together.
Taking the result modulo m.
The modulo operation ensures that the final result is a valid index.
For the string "inside code":
The sum of the ASCII codes is 1079.
If the table has m=30 slots:
Therefore, the value associated with "inside code" would be placed at index 29.
Determinism
A hash function must be deterministic.
The same key must always produce the same hash value.
This requirement is essential:
During insertion, the key is converted into an index.
During lookup, the same key is converted again.
If the hash function returned different results, the lookup might search in a different location from the one used during insertion.
For example, if "inside code" produced 29 during insertion but 12 during lookup, the value would not be found at the expected location.
Characteristics of a Good Hash Function
A good hash function should have several properties:
Deterministic: The same key always produces the same hash.
Even distribution: Keys should be spread as evenly as possible across the available indices.
Computational efficiency: The hash should be calculated quickly.
Good use of table capacity: The function should be capable of reaching most or all available slots.
Low collision rate: Different keys should rarely produce the same index.
Applications of Hash Tables
Phone Agenda
A phone agenda associates people with phone numbers:
Key: A person’s name
Value: The person’s phone number
To find a phone number:
Hash the person’s name.
Use the resulting index to access the relevant slot.
Retrieve the associated phone number.
Word Counter
A word counter stores how many times each word appears in a text:
Key: A word
Value: The number of occurrences of that word
For example, after processing a text, the table might conceptually contain:
"algorithm"→ 4"hash"→ 7"table"→ 3
When a word appears again, its stored count is updated.
Dictionary
A dictionary maps words to definitions:
Key: A word
Value: Its definition
To retrieve a definition, the word is hashed and the associated value is found at the resulting location.
Cryptography
Hashing also has applications in cryptography, although cryptographic hashing has additional requirements beyond the basic hash functions used for hash tables. Cryptographic hash functions are designed for security-related purposes such as integrity checking and secure data processing.
Collisions
Definition of a Collision
A collision occurs when two different keys produce the same hash value or array index.
For example:
"Samy Sterious"hashes to index 14."Khaled Anas"also hashes to index 14.
The keys are different, but they map to the same slot.
A collision occurs when two different keys in a hash table have the same hash value.
Collisions are unavoidable in most hash tables because:
The number of possible keys may be extremely large or infinite.
The table has only a finite number of slots.
For example, a table with m=30 slots can produce only 30 possible indices, from 0 to 29, even though there may be infinitely many possible strings.
The Pigeonhole Principle and Collisions
The Pigeonhole principle states that if more objects are placed into fewer containers, at least one container must contain multiple objects.
Applied to hash tables:
Keys are the objects.
Array slots are the containers.
Hash values determine the containers.
If more distinct keys are inserted than there are available slots, at least two keys must share a slot.
Even when the number of keys does not exceed the number of slots, collisions may still occur because the hash function may map multiple keys to the same index.
Collision-Handling Techniques
Separate Chaining
Separate chaining handles collisions by allowing each array slot to contain a linked list rather than a single value.
Each node in the linked list stores:
The key
The associated value
A pointer to the next node
When multiple keys hash to the same index, their key/value pairs are placed in the linked list at that index.
Example
If three keys hash to index 13, the slot at index 13 contains a linked list of length 3:
Node 1: First key/value pair
Node 2: Second key/value pair
Node 3: Third key/value pair
The array slot itself stores a reference to the linked list.
Searching with Separate Chaining
Suppose "Khaled Anas" hashes to index 14. The table identifies the linked list at index 14, but the list may contain values for several different keys.
The search process is:
Hash
"Khaled Anas"to obtain index 14.Access the linked list at index 14.
Traverse the nodes.
Compare each stored key with
"Khaled Anas".Return the value from the matching node.
This is why each node must store the key as well as the value. Storing only values would make it impossible to determine which value belongs to the requested key.
Advantages and Limitations
Advantage: Multiple key/value pairs can occupy the same slot.
Limitation: Long linked lists increase search time.
Important requirement: Each node must retain its key so that collisions can be resolved correctly.
Open Addressing
Open addressing keeps at most one key/value pair in each table slot.
When the desired slot is occupied, the hash table searches for another available slot. This search process is called probing.
The alternative position is determined by a probing strategy.
Linear Probing
Linear probing checks consecutive slots until an empty slot is found.
For example:
A 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 key/value pair there.
The table must store the key in addition to the value. During lookup, the same probing sequence is followed, and the stored keys are compared to identify the requested one.
Advantages and Limitations
Advantage: It does not require linked-list nodes or additional list structures.
Limitation: Searches may require checking multiple locations.
Important requirement: The probing strategy must be applied consistently during insertion and lookup.
Perfect Hashing
Definition
A perfect hash function maps a known set of keys to table slots without producing any collisions.
Perfect hashing is possible when:
The set of keys is known in advance.
The number of keys does not exceed the number of available slots.
A function can be found that maps every key to a distinct index.
For example, 20 known keys could potentially be mapped to 30 slots without collisions.
Perfect hashing maps a specific set of keys to distinct hash values.
Perfect hashing is not always practical because:
The keys may not be known ahead of time.
New keys may be inserted later.
Constructing a suitable function may be difficult.
The set of possible keys may be extremely large.
For general-purpose hash tables, collision handling is therefore normally required.
Designing a Good Hash Function
Even Distribution
A good hash function should distribute keys across all possible hash values with approximately equal probability.
Suppose a table has 30 indices, but a hash function produces almost all results between 0 and 4. Then many keys will be concentrated in only five slots, creating numerous collisions.
A better function spreads keys throughout the full range from 0 to 29.
Poor Distribution
A poor hash function may cause:
Many keys to map to the same small group of indices.
Long linked lists when using separate chaining.
Long probing sequences when using open addressing.
Slower insertion, lookup, and deletion.
Good Distribution
A good hash function:
Uses the entire table effectively.
Gives each hash value roughly the same probability.
Reduces the concentration of keys.
Helps maintain short collision chains or probing sequences.
Problems with the Simple ASCII-Sum Function
The simple ASCII-sum hash function illustrates the basic idea, but it has important weaknesses.
Order Insensitivity
The function produces the same hash for strings that contain the same characters in a different order.
For example:
"abc""acb"
Both contain the same characters, so their ASCII-code sums are identical.
Because strings are order-sensitive, these strings should generally be treated as different inputs. A hash function that ignores character order creates unnecessary collisions among all permutations of the same characters.
Limited Reachable Range
Suppose keys are strings:
At most 20 characters long.
Containing only alphabetical letters.
With the highest possible character code equal to 122.
The maximum ASCII sum is:
Therefore, this hash function cannot produce a result greater than 2440 in that setting, regardless of the table’s capacity.
If the table has 2500 slots:
Indices above 2440 cannot be produced.
Those slots remain permanently unused.
Increasing the table size does not distribute keys across the newly added slots.
Rehashing may fail to reduce collisions because the hash function still restricts keys to the same limited range.
A better hash function should incorporate character order and be capable of distributing keys across the table’s full range.
Rehashing
Definition and Purpose
Rehashing is the process of creating a new hash table with more slots and inserting all existing key/value pairs into it again.
A common strategy is to double the capacity:
The pairs must be inserted again because the table capacity affects the hash computation, usually through the modulo operation. When the capacity changes, keys may receive different indices.
Rehashing Process
Save the old array of slots.
Increase the table capacity.
Reset the element count.
Create a new empty array of slots.
Recalculate the hash for every existing key using the new capacity.
Insert every key/value pair into the new table.
Discard or release the old table.
Rehashing increases the range of possible positions and generally decreases the number of collisions.
Why Rehashing Is Needed
If a table has too few slots, many keys must share locations. For example, inserting 50 keys into 10 slots gives an average of:
elements per slot.
That produces long chains in separate chaining or crowded probing sequences in open addressing. Increasing the capacity provides more room for distribution.
Load Factor
The ratio of stored elements to table slots is:
where:
n is the number of stored elements.
m is the number of slots.
This ratio measures how full the hash table is.
Open Addressing
In open addressing, each slot contains at most one element. Therefore:
A ratio of 0 means the table is empty.
A ratio of 1 means every slot is occupied.
Separate Chaining
In separate chaining, each slot can contain multiple elements. Therefore, n may exceed m.
For example:
A load ratio of 2.5 means that there are, on average, 2.5 elements per slot, although the actual distribution may not be uniform.
Definition of Load Factor
The load factor is the maximum allowed value of mn before rehashing occurs.
For example, if the load factor is 0.75:
A table with 100 slots can hold the first 75 elements without rehashing.
Inserting the 76th element causes the ratio to exceed 0.75.
The table is then rehashed with a larger capacity.
A value of 0.75 is commonly used as a reasonable default, but the best value depends on the desired balance between speed and memory usage.
Load Factor as a Time–Space Tradeoff
Lower Load Factor
A lower load factor causes rehashing to occur earlier.
More slots are available relative to the number of elements.
Fewer collisions occur.
Lookup, insertion, and deletion are generally faster.
More memory is used.
More slots may remain empty.
Higher Load Factor
A higher load factor allows the table to become fuller before rehashing.
Fewer slots are allocated.
Memory usage is lower.
More collisions occur.
Probing sequences or linked lists become longer.
Operations may take more time.
A lower load factor prioritizes time efficiency, while a higher load factor prioritizes space efficiency.
A table may also support shrinking when it becomes too empty. If mn falls below a lower threshold, the table can be rehashed into a smaller table to reduce wasted space.
Hash Table Implementation with Separate Chaining
A simple separate-chaining implementation can be organized into nodes, linked lists, and a hash table.
Node
Each node represents one key/value pair and contains:
A key
A value
A pointer to the next node
For a string-based implementation, the key may be restricted to strings. General-purpose hash tables can support additional key types if those types can be hashed reliably.
Linked List
Each slot contains a linked list. The linked list needs operations for:
Inserting a node
Searching for a node by key
Deleting a node by key
Inserting into the Linked List
Insertion can occur at the beginning of the list:
Create a new node.
Set the new node’s next pointer to the current head.
Make the new node the head.
This operation does not require traversal.
Searching the Linked List
To search for a key:
Start at the head.
Compare the current node’s key with the requested key.
If they match, return the node.
Otherwise, follow the next pointer.
Continue until a match is found or the end of the list is reached.
Return
nullif no matching key exists.
Deleting from the Linked List
To delete a node:
Traverse the list while examining the next node’s key.
When the target key is found, bypass that node.
Link the preceding node directly to the target node’s successor.
Report whether deletion occurred.
The deletion operation returns success if the key was found and removed; otherwise, it reports failure.
Hash Table Components
A hash table contains four main pieces of state:
Capacity: The number of slots, initially perhaps 30.
Size: The number of stored key/value pairs, initially 0.
Load factor: The threshold that determines when rehashing occurs, such as 0.75.
Slots array: An array in which each slot contains a linked list.
Typical hash table methods include:
A hash function
A rehashing method
An insertion or update method
A key-existence search method
A value-retrieval method
A deletion method
Inserting or Updating a Key/Value Pair
An insertion operation may either add a new pair or update the value of an existing key.
Process
Calculate the key’s hash.
Convert the hash into a valid slot index.
Access the linked list at that index.
Search the list for the key.
If the key exists:
Replace its existing value.
Do not increase the table size.
If the key does not exist:
Create and insert a new node.
Increase the size by one.
Check the ratio mn.
If the ratio exceeds the load factor, rehash the table.
Updating an existing key is different from inserting a new key because it does not create an additional element.
Searching for a Key
To determine whether a key exists:
Hash the key.
Calculate its slot index.
Search the linked list at that index.
If a node is found, the key exists.
If the search reaches the end without a match, the key does not exist.
Getting a Value
To retrieve a value:
Hash the key.
Access the linked list at the resulting index.
Search for a node whose key matches.
Return the node’s value if found.
Return
nullor an equivalent absence indicator if the key is not found.
Deleting a Key/Value Pair
To delete a pair:
Hash the key.
Access the linked list at the corresponding index.
Delete the node with that key.
If deletion succeeds, decrement the table size.
Optionally shrink the table if its load becomes sufficiently low.
Space Complexity
The space complexity of a data structure describes how its memory usage grows as the number of stored elements increases.
For a hash table using separate chaining, space is determined mainly by:
The number of nodes.
The number of array slots.
If the table stores n elements:
It contains n nodes.
The number of slots is generally proportional to n, represented as cn for some constant c determined partly by the load factor.
Therefore, total space grows linearly:
A hash table has O(n) space complexity.
The constant factor may vary depending on the load factor and collision-handling method, but the overall asymptotic growth remains linear.
Time Complexity
The following average-case results assume:
A good hash function.
Reasonably even key distribution.
A controlled load factor.
Collision chains that remain short.
Linked-List Operations
Inserting a Node
Inserting at the head requires changing a small, fixed number of references. It does not depend on the list length.
Searching for a Node
Searching may require examining every node in a list. If the list has length l:
Deleting a Node
Deletion also requires finding the target node, so it has complexity:
Hash Function Complexity
The hash function is treated as O(1) relative to the number of elements in the table because its runtime does not depend on n.
In some situations, hashing a key may depend on the key size k, giving a complexity closer to O(k). However, hashing can still be considered O(1) when:
Keys have a fixed-size representation, such as standard integers.
The function examines only a fixed number of characters.
Keys are known to have a bounded maximum size.
The analysis focuses on dependence on the number of stored elements.
The important point is that the hash calculation does not become slower merely because the table contains more elements.
Insertion
Insertion consists of several stages:
Calculate the hash: O(1) under the usual assumption.
Search the selected chain for the key.
Update the value if the key exists.
Otherwise, insert a new node at the head.
Possibly rehash the table.
Best Case
If there are no collisions, the selected linked list has length 0 or 1. Searching takes constant time:
Worst Case
If all n elements occupy one linked list, searching requires traversing the entire list:
Average Case
With a good hash function and suitable rehashing, chains generally remain short. Searching within a chain is therefore treated as:
The direct insertion at the head is also O(1).
Rehashing and Amortized Complexity
A rehash operation requires moving all existing elements into a new table, so one rehash costs:
However, rehashing occurs infrequently. If the capacity is increased substantially, such as by doubling it, many ordinary insertions occur between rehashes.
When the total cost of many insertions is averaged across all those insertions, the occasional expensive rehash is distributed over the inexpensive operations. This is called amortized complexity.
Thus, insertion has:
Average collision-handling cost: O(1)
Amortized cost including rehashing: O(1)
Worst-case cost: O(n)
Lookup
Lookup determines whether a key exists.
Hash the key: O(1).
Search the chain at the resulting index.
With a good distribution, the chain is short on average.
Therefore:
Average case: O(1)
Worst case: O(n)
Retrieving a Value
Retrieving the value associated with a key follows the same procedure as lookup:
Calculate the hash.
Search the relevant chain.
Return the value from the matching node.
Therefore:
Average case: O(1)
Worst case: O(n)
Deletion
Deletion requires:
Hashing the key.
Searching the corresponding chain.
Removing the matching node.
Therefore:
Average case: O(1)
Worst case: O(n)
Complexity Summary
Average and Amortized Performance
Insert or update: O(1) average and amortized
Search for a key: O(1) average
Get a value: O(1) average
Delete a key/value pair: O(1) average
Worst-Case Performance
Insert: O(n)
Search: O(n)
Get: O(n)
Delete: O(n)
The worst case occurs when many keys collide and are concentrated in one chain or require a long probing sequence.
A good hash function, suitable table capacity, and appropriate rehashing reduce the likelihood of worst-case behavior.
Why Use a Hash Table?
A simple array can store values, but finding a value associated with a particular key may require a linear search through the array.
If the array contains n elements, a linear search can require:
A hash table uses the key to calculate a likely location directly. Under normal conditions, the main operations take constant time on average:
This makes hash tables especially useful when key/value pairs must be accessed repeatedly.
Many programming languages provide built-in hash table implementations:
Python:
dictJava:
HashMapC++:
unordered_map
These built-in structures are generally preferable for ordinary programming tasks because they are optimized and already handle implementation details such as hashing, collisions, resizing, and key comparison.
The Two Sum Problem
The two sum problem asks for the indices of two elements in an array whose values add up to a target k.
A naive approach checks every pair of elements:
There are many possible pairs.
The resulting time complexity is:
A hash table improves the process:
Traverse the array.
For each element x, calculate the required complement:
Check whether k−x has already been stored in the hash table.
If it has, return the stored index and the current index.
If it has not, store x together with its current index.
Continue until a matching pair is found.
Because hash-table lookup is O(1) on average and the array is traversed once, the overall time complexity becomes:
The hash table stores each previously encountered element and the index where it appeared.
Key and Value Requirements
Key Uniqueness
Keys in a hash table must be unique.
A table should not contain multiple separate entries with exactly the same key. If an insertion uses a key that already exists, the usual behavior is to update the existing value.
Values do not need to be unique:
Multiple keys may map to the same value.
Different people may share the same phone number.
Multiple words may have identical definitions.
Several keys can legally store the same object or number.
Key Immutability
A key must be immutable.
The hash table depends on the fact that a key always produces the same hash value. If a key changes after insertion, its new hash may point to a different slot from the one used originally.
Mutable-Key Problem
Suppose an array is used as a key:
The array initially has a particular contents and hashes to 56.
The array is inserted into the table at the location associated with 56.
The array is modified by adding or changing an element.
Hashing the modified array may produce a different result.
A later lookup may search at the new location rather than the original one.
The entry may still exist in the table, but the hash table can no longer locate it reliably using the changed key.
Suitable Key Types
Common immutable key types include:
Integers
Strings
Tuples, provided their contents are also hashable and immutable
Common mutable types that should not be used as keys include:
Arrays or lists
Sets
Other objects whose hash-relevant state can change
Values May Be Mutable
Values do not need to be immutable because the hash table does not use a value to determine its location.
A value may be:
An integer
A string
An array
A set
Another hash table
A complex object
Keys must be unique and immutable; values do not need to be unique or immutable.
Essential Definitions
Hashing: The process of converting a key into a fixed-size value.
Hash: The result produced by hashing a key.
Hash function: A deterministic function that calculates a key’s hash.
Hash table: A data structure that stores key/value pairs and uses hashing to determine storage locations.
Slot or bucket: A location in the table’s underlying array.
Collision: The event in which two different keys produce the same hash value or index.
Separate chaining: Collision handling by storing multiple key/value pairs in a linked list at the same slot.
Open addressing: Collision handling by probing for an alternative empty slot.
Linear probing: Open addressing that checks consecutive slots until an available one is found.
Perfect hashing: Mapping a known set of keys to distinct indices without collisions.
Rehashing: Creating a larger or smaller table and reinserting existing key/value pairs.
Load factor: The maximum permitted value of mn before rehashing occurs.
Amortized complexity: The average cost per operation over a long sequence that includes occasional expensive operations such as rehashing.

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