1. Home
  2. Explore
  3. Computer Science
  4. Hashing and Hash Tables

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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: 292929

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:

  1. The book title is used as the key.

  2. A hash function converts the title into a number.

  3. That number identifies the book’s position in the library.

  4. 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 mmm slots, valid array indices range from 000 through m−1m-1m−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:

  1. Accepts a key as input.

  2. Performs computations on that key.

  3. Returns a hash value, usually corresponding to an array index.

For a hash table containing mmm slots, the hash function should produce a value in the range:

0≤h(k)≤m−10 \leq h(k) \leq m-10≤h(k)≤m−1

where h(k)h(k)h(k) is the hash of key kkk.

A Simple Hash Function for Strings

One basic string hash function can be created by:

  1. Converting every character to its ASCII code.

  2. Adding the ASCII codes together.

  3. Taking the result modulo mmm.

The modulo operation ensures that the final result is a valid index.

h(k)=(∑ASCII codes of characters in k) mod mh(k) = \left(\sum \text{ASCII codes of characters in } k\right) \bmod mh(k)=(∑ASCII codes of characters in k)modm

For the string "inside code":

  • The sum of the ASCII codes is 107910791079.

  • If the table has m=30m=30m=30 slots:

1079 mod 30=291079 \bmod 30 = 291079mod30=29

Therefore, the value associated with "inside code" would be placed at index 292929.

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 292929 during insertion but 121212 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:

  1. Hash the person’s name.

  2. Use the resulting index to access the relevant slot.

  3. 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" → 444

  • "hash" → 777

  • "table" → 333

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 141414.

  • "Khaled Anas" also hashes to index 141414.

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=30m=30m=30 slots can produce only 303030 possible indices, from 000 to 292929, 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 131313, the slot at index 131313 contains a linked list of length 333:

  • 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 141414. The table identifies the linked list at index 141414, but the list may contain values for several different keys.

The search process is:

  1. Hash "Khaled Anas" to obtain index 141414.

  2. Access the linked list at index 141414.

  3. Traverse the nodes.

  4. Compare each stored key with "Khaled Anas".

  5. 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:

  1. A key hashes to index 141414.

  2. Index 141414 is occupied.

  3. Check index 151515.

  4. Index 151515 is occupied.

  5. Check index 161616.

  6. Index 161616 is occupied.

  7. Check index 171717.

  8. Index 171717 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, 202020 known keys could potentially be mapped to 303030 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 303030 indices, but a hash function produces almost all results between 000 and 444. Then many keys will be concentrated in only five slots, creating numerous collisions.

A better function spreads keys throughout the full range from 000 to 292929.

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 202020 characters long.

  • Containing only alphabetical letters.

  • With the highest possible character code equal to 122122122.

The maximum ASCII sum is:

20×122=244020 \times 122 = 244020×122=2440

Therefore, this hash function cannot produce a result greater than 244024402440 in that setting, regardless of the table’s capacity.

If the table has 250025002500 slots:

  • Indices above 244024402440 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:

mnew=2moldm_{\text{new}} = 2m_{\text{old}}mnew​=2mold​

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

  1. Save the old array of slots.

  2. Increase the table capacity.

  3. Reset the element count.

  4. Create a new empty array of slots.

  5. Recalculate the hash for every existing key using the new capacity.

  6. Insert every key/value pair into the new table.

  7. 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 505050 keys into 101010 slots gives an average of:

5010=5\frac{50}{10} = 51050​=5

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:

nm\frac{n}{m}mn​

where:

  • nnn is the number of stored elements.

  • mmm 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:

0≤nm≤10 \leq \frac{n}{m} \leq 10≤mn​≤1
  • A ratio of 000 means the table is empty.

  • A ratio of 111 means every slot is occupied.

Separate Chaining

In separate chaining, each slot can contain multiple elements. Therefore, nnn may exceed mmm.

For example:

5020=2.5\frac{50}{20} = 2.52050​=2.5

A load ratio of 2.52.52.5 means that there are, on average, 2.52.52.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 nm\frac{n}{m}mn​ before rehashing occurs.

For example, if the load factor is 0.750.750.75:

  • A table with 100100100 slots can hold the first 757575 elements without rehashing.

  • Inserting the 767676th element causes the ratio to exceed 0.750.750.75.

  • The table is then rehashed with a larger capacity.

A value of 0.750.750.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 nm\frac{n}{m}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:

  1. Create a new node.

  2. Set the new node’s next pointer to the current head.

  3. Make the new node the head.

This operation does not require traversal.

Searching the Linked List

To search for a key:

  1. Start at the head.

  2. Compare the current node’s key with the requested key.

  3. If they match, return the node.

  4. Otherwise, follow the next pointer.

  5. Continue until a match is found or the end of the list is reached.

  6. Return null if no matching key exists.

Deleting from the Linked List

To delete a node:

  1. Traverse the list while examining the next node’s key.

  2. When the target key is found, bypass that node.

  3. Link the preceding node directly to the target node’s successor.

  4. 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 303030.

  • Size: The number of stored key/value pairs, initially 000.

  • Load factor: The threshold that determines when rehashing occurs, such as 0.750.750.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

  1. Calculate the key’s hash.

  2. Convert the hash into a valid slot index.

  3. Access the linked list at that index.

  4. Search the list for the key.

  5. If the key exists:

    • Replace its existing value.

    • Do not increase the table size.

  6. If the key does not exist:

    • Create and insert a new node.

    • Increase the size by one.

  7. Check the ratio nm\frac{n}{m}mn​.

  8. 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:

  1. Hash the key.

  2. Calculate its slot index.

  3. Search the linked list at that index.

  4. If a node is found, the key exists.

  5. If the search reaches the end without a match, the key does not exist.

Getting a Value

To retrieve a value:

  1. Hash the key.

  2. Access the linked list at the resulting index.

  3. Search for a node whose key matches.

  4. Return the node’s value if found.

  5. Return null or an equivalent absence indicator if the key is not found.

Deleting a Key/Value Pair

To delete a pair:

  1. Hash the key.

  2. Access the linked list at the corresponding index.

  3. Delete the node with that key.

  4. If deletion succeeds, decrement the table size.

  5. 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:

  1. The number of nodes.

  2. The number of array slots.

If the table stores nnn elements:

  • It contains nnn nodes.

  • The number of slots is generally proportional to nnn, represented as cnc ncn for some constant ccc determined partly by the load factor.

Therefore, total space grows linearly:

O(n)+O(cn)=O(n)O(n) + O(cn) = O(n)O(n)+O(cn)=O(n)

A hash table has O(n)O(n)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.

O(1)O(1)O(1)

Searching for a Node

Searching may require examining every node in a list. If the list has length lll:

O(l)O(l)O(l)

Deleting a Node

Deletion also requires finding the target node, so it has complexity:

O(l)O(l)O(l)

Hash Function Complexity

The hash function is treated as O(1)O(1)O(1) relative to the number of elements in the table because its runtime does not depend on nnn.

In some situations, hashing a key may depend on the key size kkk, giving a complexity closer to O(k)O(k)O(k). However, hashing can still be considered O(1)O(1)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:

  1. Calculate the hash: O(1)O(1)O(1) under the usual assumption.

  2. Search the selected chain for the key.

  3. Update the value if the key exists.

  4. Otherwise, insert a new node at the head.

  5. Possibly rehash the table.

Best Case

If there are no collisions, the selected linked list has length 000 or 111. Searching takes constant time:

O(1)O(1)O(1)

Worst Case

If all nnn elements occupy one linked list, searching requires traversing the entire list:

O(n)O(n)O(n)

Average Case

With a good hash function and suitable rehashing, chains generally remain short. Searching within a chain is therefore treated as:

O(1) averageO(1) \text{ average}O(1) average

The direct insertion at the head is also O(1)O(1)O(1).

Rehashing and Amortized Complexity

A rehash operation requires moving all existing elements into a new table, so one rehash costs:

O(n)O(n)O(n)

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)O(1)O(1)

  • Amortized cost including rehashing: O(1)O(1)O(1)

  • Worst-case cost: O(n)O(n)O(n)


Lookup

Lookup determines whether a key exists.

  1. Hash the key: O(1)O(1)O(1).

  2. Search the chain at the resulting index.

  3. With a good distribution, the chain is short on average.

Therefore:

  • Average case: O(1)O(1)O(1)

  • Worst case: O(n)O(n)O(n)

Retrieving a Value

Retrieving the value associated with a key follows the same procedure as lookup:

  1. Calculate the hash.

  2. Search the relevant chain.

  3. Return the value from the matching node.

Therefore:

  • Average case: O(1)O(1)O(1)

  • Worst case: O(n)O(n)O(n)

Deletion

Deletion requires:

  1. Hashing the key.

  2. Searching the corresponding chain.

  3. Removing the matching node.

Therefore:

  • Average case: O(1)O(1)O(1)

  • Worst case: O(n)O(n)O(n)


Complexity Summary

Average and Amortized Performance

  • Insert or update: O(1)O(1)O(1) average and amortized

  • Search for a key: O(1)O(1)O(1) average

  • Get a value: O(1)O(1)O(1) average

  • Delete a key/value pair: O(1)O(1)O(1) average

Worst-Case Performance

  • Insert: O(n)O(n)O(n)

  • Search: O(n)O(n)O(n)

  • Get: O(n)O(n)O(n)

  • Delete: O(n)O(n)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 nnn elements, a linear search can require:

O(n)O(n)O(n)

A hash table uses the key to calculate a likely location directly. Under normal conditions, the main operations take constant time on average:

O(1)O(1)O(1)

This makes hash tables especially useful when key/value pairs must be accessed repeatedly.

Many programming languages provide built-in hash table implementations:

  • Python: dict

  • Java: HashMap

  • C++: 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 kkk.

A naive approach checks every pair of elements:

  • There are many possible pairs.

  • The resulting time complexity is:

O(n2)O(n^2)O(n2)

A hash table improves the process:

  1. Traverse the array.

  2. For each element xxx, calculate the required complement:

k−xk-xk−x
  1. Check whether k−xk-xk−x has already been stored in the hash table.

  2. If it has, return the stored index and the current index.

  3. If it has not, store xxx together with its current index.

  4. Continue until a matching pair is found.

Because hash-table lookup is O(1)O(1)O(1) on average and the array is traversed once, the overall time complexity becomes:

O(n)O(n)O(n)

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:

  1. The array initially has a particular contents and hashes to 565656.

  2. The array is inserted into the table at the location associated with 565656.

  3. The array is modified by adding or changing an element.

  4. Hashing the modified array may produce a different result.

  5. 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 nm\frac{n}{m}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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent