Hashing in Data Structure | Hash Table and Hash Functions

Hashing in Data Structure

Hashing is one of the most powerful techniques used in Data Structures for storing and retrieving data efficiently. It provides a fast method to access information without searching through all available records. Modern software applications, databases, operating systems, compilers, and search engines rely heavily on hashing techniques to improve performance.

The primary goal of hashing is to reduce the time required to search, insert, and delete data. Instead of examining every element individually, hashing calculates a storage location directly using a mathematical formula called a hash function.

Because of its speed and efficiency, hashing is considered one of the most important topics in computer science and software development.


What is Hashing?

Hashing is a technique that converts a key into a fixed-size value called a hash value. This hash value determines the location where data will be stored in memory.

Rather than searching sequentially through all records, the system calculates the hash value and directly accesses the required memory location.

This direct access mechanism makes hashing significantly faster than many traditional searching methods.


Simple Definition of Hashing

Hashing is the process of transforming a key into an index value that can be used to store and retrieve data efficiently.


Need for Hashing

As the amount of data grows, searching through records becomes slower. Traditional searching methods may require checking multiple elements before finding the desired data.

Hashing solves this problem by providing direct access to information.

Reasons for Using Hashing


Real-Life Example of Hashing

Consider a library containing thousands of books. Without a proper system, finding a specific book may take a long time.

Now imagine every book is assigned a unique shelf number based on its category. By using that shelf number, the librarian can directly locate the book.

Hashing works in a similar manner. Instead of searching every record, it calculates the storage location directly.


Basic Components of Hashing

A hashing system mainly consists of the following components:


What is a Key?

A key is the value used to identify a record.

Examples include:

The key is passed to the hash function to determine the storage location.


What is a Hash Function?

A Hash Function is a mathematical formula that converts a key into an index value.

The generated index specifies where data will be stored inside the hash table.

General Representation

Hash Function(Key) = Index

Example of Hash Function

Suppose a hash table contains 10 locations.

Hash Function

H(Key) = Key % 10

If the key value is:

Key = 47
47 % 10 = 7

The data will be stored at index position 7.


Another Example

Key = 84
84 % 10 = 4

The data will be stored at index position 4.


What is a Hash Table?

A Hash Table is a data structure that stores data according to hash values generated by a hash function.

Each position inside the table is called a bucket or slot.

Data is inserted into the slot determined by the hash function.


Hash Table Structure

Index      Data
0          -
1          -
2          32
3          -
4          84
5          -
6          -
7          47
8          -
9          -

In this example, keys 32, 84, and 47 are stored according to their hash values.


Working of Hashing

The working of hashing follows a straightforward process.

Step 1

Take the input key.

Step 2

Apply the hash function.

Step 3

Generate a hash value.

Step 4

Store the data at the calculated index.

Step 5

Use the same process for retrieval.


Hashing Operations

A hash table supports three primary operations.

1. Insertion

Stores data in the location generated by the hash function.

2. Searching

Retrieves data directly using the hash value.

3. Deletion

Removes data from the corresponding location.


Characteristics of a Good Hash Function

A good hash function should distribute data uniformly throughout the hash table, since a poorly designed function can cause many keys to cluster into the same slots and slow the table down.

Important Characteristics


Complexity Analysis of Hashing

Operation Average Complexity
Insertion O(1)
Searching O(1)
Deletion O(1)

These complexities make hashing one of the fastest data storage and retrieval techniques, though they represent the average case — the worst case degrades to O(n) when many keys collide, which is why collision handling matters so much.


Collision in Hashing

In the previous section, we learned that a hash function converts a key into an index value and stores data in a hash table. However, a practical problem arises when two or more different keys generate the same hash value. This situation is known as a collision.

Collisions are unavoidable in most hashing systems because the number of possible keys is usually much larger than the number of available storage locations. Therefore, every efficient hashing implementation must include a strategy for handling collisions.


What is a Collision?

A collision occurs when two different keys are assigned to the same location in a hash table.

Example

Consider the following hash function:

H(Key) = Key % 10

Now calculate the hash values:

H(25) = 25 % 10 = 5
H(35) = 35 % 10 = 5

Both keys produce index 5. Since only one location exists at index 5, a collision occurs.


Why Do Collisions Occur?

Collisions occur because a hash table has a limited number of slots, while the number of possible keys can be extremely large.

Main Causes of Collisions


Need for Collision Handling

Without collision handling techniques, new data may overwrite existing records, causing data loss and incorrect retrieval.

Collision handling ensures that all records can be stored and accessed correctly even when multiple keys generate the same index.


Collision Resolution Techniques

Several techniques are available for managing collisions in a hash table.

Each technique has its own advantages and limitations.


Separate Chaining

Separate Chaining is one of the most common collision handling methods. In this technique, each slot of the hash table stores a linked list.

When multiple keys map to the same index, they are stored in the linked list associated with that index.


Example of Separate Chaining

Suppose the following keys are inserted:

15, 25, 35

Using:

H(Key) = Key % 10

All keys produce index 5.

Index 5
15 → 25 → 35

The linked list stores all colliding elements.


Advantages of Separate Chaining


Disadvantages of Separate Chaining


Open Addressing

Open Addressing stores all elements directly within the hash table itself.

When a collision occurs, the algorithm searches for another empty slot according to a predefined rule.

The most common open addressing techniques are:


Linear Probing

Linear Probing is the simplest open addressing technique. When a collision occurs, the algorithm checks the next available position sequentially.


Linear Probing Formula

New Index = (Hash Value + i) % Table Size

Where i represents the number of attempts.


Example of Linear Probing

Hash Function:

H(Key) = Key % 10

Insert:

25 → Index 5
35 → Index 5 (Collision)

Check next location:

Index 6 → Empty

Store 35 at index 6.


Advantages of Linear Probing


Disadvantages of Linear Probing


Quadratic Probing

Quadratic Probing reduces clustering by increasing the probing distance quadratically.


Quadratic Probing Formula

New Index =

(Hash Value + i²) % Table Size

Example of Quadratic Probing

Suppose:

H(25) = 5
H(35) = 5

Collision occurs.

Try:

5 + 1² = 6
If occupied
5 + 2² = 9
If empty, insert there.

Advantages of Quadratic Probing


Disadvantages of Quadratic Probing


Double Hashing

Double Hashing uses two different hash functions to determine the next position.

It is considered one of the most effective collision resolution techniques.


Double Hashing Formula

Index =
(H1(Key) + i × H2(Key))
% Table Size

Where:


Advantages of Double Hashing


Disadvantages of Double Hashing


Load Factor in Hashing

The Load Factor measures how full a hash table is.

It is represented by the symbol α (alpha).


Load Factor Formula

Load Factor (α)
= Number of Elements
/ Table Size

Example

Suppose:

Elements = 8
Table Size = 10
α = 8 / 10
α = 0.8

This means 80% of the table is occupied.


Importance of Load Factor


Rehashing

When the load factor becomes too high, collisions increase significantly. To maintain efficiency, the hash table size is increased and all existing elements are reinserted.

This process is called Rehashing.


Steps in Rehashing

  1. Create a larger hash table.
  2. Apply hash function again.
  3. Reinsert all elements.
  4. Replace old table.

Advantages of Rehashing


Complexity Analysis of Collision Handling

Operation Average Case Worst Case
Insertion O(1) O(n)
Searching O(1) O(n)
Deletion O(1) O(n)

Applications of Hashing

Hashing is one of the most widely used techniques in modern computing. Although the basic concept of hashing is simple, its applications are found in almost every software system. From websites and databases to operating systems and cybersecurity tools, hashing plays an important role in improving speed, efficiency, and reliability.

The primary advantage of hashing is its ability to provide near-instant access to data. Because of this capability, hashing is used whenever fast searching, insertion, or retrieval of information is required.


Hashing in Database Management Systems

Database systems store millions of records. Searching through every record sequentially would be extremely slow and inefficient.

Hashing helps databases locate records quickly by converting a search key into a storage location.

Example

Consider a student database containing thousands of records. If a user searches for a roll number, the database can use hashing to directly locate the record instead of scanning the entire table.

Benefits in Databases


Hashing in Password Security

Modern applications do not store passwords in plain text format. Instead, passwords are converted into hash values before storage.

When a user enters a password during login, the system hashes the entered password and compares the generated hash with the stored hash value.

If both values match, access is granted.

Advantages


Cryptographic Hash Functions

Cryptographic hashing is a specialized form of hashing used in cybersecurity and digital security applications.

A cryptographic hash function generates a fixed-size output regardless of the input size.

Characteristics


Hashing in Search Engines

Search engines process enormous amounts of information every second. Efficient indexing is essential for delivering results quickly.

Hashing helps search engines organize and retrieve data efficiently.

Uses in Search Engines


Hashing in Compilers

Compilers use symbol tables to store information about variables, functions, constants, and identifiers.

Hash tables provide an efficient mechanism for managing these symbol tables.

Benefits


Hashing in Operating Systems

Operating systems use hashing for several internal operations.

Examples

Hash tables allow the operating system to locate resources quickly.


Hashing in Caching Systems

Caching systems temporarily store frequently accessed information.

Hashing enables quick access to cached data by mapping requests directly to storage locations.

Applications


Hashing in Networking

Computer networks use hashing to improve routing, packet processing, and data verification.

Applications


Hashing in Blockchain Technology

Blockchain systems use cryptographic hashing extensively to secure transactions and maintain data integrity.

Every block contains a hash value that connects it to the previous block.

Benefits


Hashing vs Array

Hash tables and arrays are both used to store data, but they operate differently.

Hashing Array
Stores data using keys. Stores data sequentially.
Fast searching. Linear searching may be required.
Average O(1) access. Direct access through index.
Collision handling required. No collisions.

Hashing vs Binary Search Tree

Hashing Binary Search Tree
Average O(1) searching. Average O(log n) searching.
No ordering of data. Data remains sorted.
Fast retrieval. Supports ordered traversal.
Uses hash functions. Uses tree structure.

Advantages of Hashing


Disadvantages of Hashing


Best Practices for Efficient Hashing


Hashing Interview Questions and Answers

1. What is Hashing, and why is it used?

Hashing is a technique that converts a key into a fixed-size index using a hash function, allowing data to be stored and retrieved directly instead of being searched sequentially. It's used because it brings average search, insertion, and deletion time down to O(1), which is far faster than scanning through records one by one.

2. What is the difference between a Hash Function, a Hash Value, and a Hash Table?

A Hash Function is the formula that does the conversion, such as H(Key) = Key % 10. The Hash Value is the output of that formula — the actual index it produces. The Hash Table is the underlying data structure whose slots are addressed using these hash values.

3. What is a Collision, and why is it unavoidable?

A collision happens when two different keys produce the same hash value and are mapped to the same slot. It's largely unavoidable because the number of possible keys is usually far larger than the number of available table slots, so some overlap is a matter of probability, not just poor design.

4. What is the difference between Separate Chaining and Open Addressing?

Separate Chaining resolves collisions by storing a linked list at each slot, so multiple keys can live at the same index. Open Addressing instead keeps everything inside the table itself and, on a collision, searches for another open slot using a rule like linear probing, quadratic probing, or double hashing.

5. Why does Linear Probing suffer from clustering, and how do Quadratic Probing and Double Hashing help?

Linear Probing checks the very next slot on a collision, which tends to bunch occupied slots together into long runs — a problem called primary clustering that slows future insertions. Quadratic Probing spaces out its probe attempts using square increments, and Double Hashing uses a second hash function entirely, both of which spread collisions more evenly across the table.

6. What is Load Factor, and why does it matter?

Load Factor is the ratio of stored elements to the total table size (α = elements / table size). It matters because a high load factor sharply increases the chance of collisions and degrades performance — most implementations trigger rehashing once the load factor crosses a certain threshold, typically around 0.7.

7. What is Rehashing, and when does it happen?

Rehashing is the process of creating a larger hash table and reinserting every existing element into it using the hash function again. It's triggered once the load factor gets too high, since a table that's nearly full will otherwise suffer from frequent, expensive collisions.

8. Why is hashing used for storing passwords instead of plain text?

Passwords are hashed rather than stored directly so that even if a database is compromised, the original passwords aren't exposed. During login, the entered password is hashed and compared against the stored hash — since cryptographic hash functions are designed to be practically impossible to reverse, the original password stays protected.

9. Why is Hashing generally faster than a Binary Search Tree for lookups?

Hashing achieves average O(1) lookups because it computes the exact storage location directly from the key, while a Binary Search Tree needs O(log n) comparisons to navigate down the tree. The trade-off is that a BST keeps data in sorted order and supports range queries, which a hash table does not.

10. What is a real-world example of hashing outside of basic data storage?

Blockchain systems are a good example — every block contains a cryptographic hash of the previous block's data, which links the chain together and makes it immediately detectable if any past block is tampered with, since changing the data would change its hash.


Summary

Hashing is one of the most important techniques in Data Structures because it provides efficient storage and retrieval of information. By converting keys into hash values, systems can access data quickly without performing extensive searches. Hashing is used extensively in databases, operating systems, compilers, networking, search engines, security systems, and modern web applications.

A solid understanding of hash functions, hash tables, collision handling, load factors, and real-world applications is essential for computer science students, software developers, and interview preparation. Mastering hashing also builds a strong foundation for advanced topics in algorithms, databases, cybersecurity, and distributed computing.



← Previous: Sorting in DS Next: File Structure →
Home Visit Our YouTube Channel