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

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,0001{,}000{,}0001,000,000 positions, numbered from 000 through 999,999999{,}999999,999. If a book title is hashed to position 472,819472{,}819472,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:

  1. Start with the key.
  2. Apply the hash function.
  3. Receive an index.
  4. Go directly to that index.
  5. 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 conceptLibrary analogy
KeyBook title
ValueBook itself
Array of slotsLibrary
IndexPosition 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 mmm slots, the hash function must produce a valid index from 000 through m−1m-1m−1.

A hash function can be represented conceptually as:

h(key)=indexh(\text{key}) = \text{index}h(key)=index

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

  1. Convert every character to its ASCII code.
  2. Add all the ASCII codes together.
  3. Calculate the result modulo mmm.

The modulo operation produces a remainder in the range from 000 through m−1m-1m−1.

For the key "inside code", suppose the sum of the ASCII codes is 107910791079 and the table has m=30m=30m=30 slots. The hash is:

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

Therefore, this hash function assigns "inside code" to index 292929.

The number 292929 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 kkk:

h(k)=the same result every timeh(k) = \text{the same result every time}h(k)=the same result every time

This 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 303030 slots:

  • "Samy Sterious" hashes to index 141414.
  • "Khaled Anas" also hashes to index 141414.

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 141414, 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 131313, the slot at index 131313 contains a linked list with three nodes:

slot 13⟶node1⟶node2⟶node3\text{slot }13 \longrightarrow \text{node}_1 \longrightarrow \text{node}_2 \longrightarrow \text{node}_3slot 13⟶node1​⟶node2​⟶node3​

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

Searching with Separate Chaining

To find a value:

  1. Hash the requested key.
  2. Go to the linked list at the resulting index.
  3. Traverse the list.
  4. Compare the requested key with the key in each node.
  5. 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:

  1. Calculate the key’s index.
  2. Search the linked list at that index.
  3. If the key already exists, update its value.
  4. 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:

  1. The 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 pair at index 171717.

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

StrategyHow collisions are handled
Separate chainingA slot contains a linked list of key/value pairs
Open addressingThe algorithm probes alternative slots
Linear probingAlternative 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 mmm slots has only mmm 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 mmm different keys are inserted into a table with mmm 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 202020 known keys and 303030 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 303030 indices, but a hash function sends most keys to indices 000 through 444. 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 101010 slots and must store 505050 keys. On average, each slot would correspond to:

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

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

  1. Save the old table.
  2. Increase the capacity, often by doubling it.
  3. Create a new, empty table.
  4. Reset the size of the table.
  5. Recalculate the index of every old key using the new capacity.
  6. 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 202020 alphabetical characters, and the largest ASCII code is 122122122. The maximum possible character-code sum is:

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

Therefore, this hash function cannot produce values greater than 244024402440 in that situation.

If a table has 250025002500 slots, the indices after 244024402440 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:

nm\frac{n}{m}mn​

where:

  • nnn is the number of stored elements
  • mmm is the number of slots

For example, if n=21n=21n=21 and m=30m=30m=30:

nm=2130=0.7\frac{n}{m}=\frac{21}{30}=0.7mn​=3021​=0.7

The load factor threshold is the maximum permitted value of this ratio before rehashing occurs.

If the threshold is 0.750.750.75, rehashing occurs when the table’s ratio exceeds 0.750.750.75. For a table with 100100100 slots:

  • The first 757575 elements do not exceed the threshold.
  • Inserting the 767676th element causes the ratio to exceed 0.750.750.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≤mn \leq mn≤m

The ratio nm\frac{n}{m}mn​ must be between 000 and 111:

  • 000 means the table is empty.
  • 111 means every slot is occupied.

Load Factor in Separate Chaining

In separate chaining, one slot can contain many elements in its linked list. Therefore, nnn can be greater than mmm.

For example, if 505050 elements are stored in 202020 slots:

nm=5020=2.5\frac{n}{m}=\frac{50}{20}=2.5mn​=2050​=2.5

The load factor can therefore exceed 111 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 factorHigher load factor
Fewer collisionsMore collisions
Faster average operationsSlower average operations
More unused spaceLess unused space
Greater memory usageLower memory usage

A threshold of 0.750.750.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:

  1. Nodes
  2. Linked lists
  3. 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 303030.
  • Size: The number of stored key/value pairs, initially 000.
  • Load factor threshold: For example, 0.750.750.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:

  1. Hash the key to calculate its index.
  2. Access the linked list at that index.
  3. Search the list for the key.
  4. If the key exists, replace its old value with the new value.
  5. If the key does not exist, insert a new node.
  6. Increase the table size if a new node was added.
  7. Check the load factor.
  8. 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:

  1. Hash the key.
  2. Go to the linked list at the resulting index.
  3. Search the list.
  4. Return true if a matching node is found.
  5. Return false otherwise.

Retrieving a Value

To retrieve a value:

  1. Hash the key.
  2. Go to the corresponding linked list.
  3. Search for the matching key.
  4. Return its value if found.
  5. Return a null-like result if the key does not exist.

Deleting a Key/Value Pair

To delete a pair:

  1. Hash the key.
  2. Go to the linked list at the calculated index.
  3. Search for the matching node.
  4. Remove it if found.
  5. 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)O(1)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 lll, the search takes:

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

Deleting a node also requires searching for it, so deletion takes:

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

Hashing Time

The hash function is considered to take:

O(1)O(1)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 000 or 111.
  • In the worst case, every key hashes to the same index, creating one list of length nnn.

The corresponding search costs are:

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

in the best case, and

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

OperationAverage complexity
Insert or updateO(1)O(1)O(1) amortized
Search for a keyO(1)O(1)O(1)
Get a valueO(1)O(1)O(1)
DeleteO(1)O(1)O(1)

The worst-case complexity of these operations can still be:

O(n)O(n)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:

  1. The nodes representing stored elements
  2. The array of slots

There are nnn nodes, one for each stored element. The number of slots is generally proportional to nnn, determined by the selected load factor. If the number of slots is ccc times the number of elements for some constant ccc, the total space remains linear:

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

Thus, a hash table has O(n)O(n)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 kkk. 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)O(n^2)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 xxx, the needed companion is:

k−xk-xk−x

The algorithm checks whether k−xk-xk−x has already been stored:

  1. Read the current element xxx.
  2. Calculate k−xk-xk−x.
  3. Look up k−xk-xk−x in the hash table.
  4. If it exists, return the previous index and the current index.
  5. Otherwise, store xxx and its index.
  6. Continue scanning.

Because each lookup and insertion takes O(1)O(1)O(1) on average, the entire algorithm takes:

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

time, improving substantially over O(n2)O(n^2)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 000.

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 565656. 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, nm\frac{n}{m}mn​, determines when rehashing occurs and balances time efficiency against memory efficiency.

With a good implementation, insertion is O(1)O(1)O(1) amortized, and searching, retrieving, and deleting are O(1)O(1)O(1) on average. The worst case remains O(n)O(n)O(n) when collisions are heavily concentrated. The total space complexity is O(n)O(n)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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent