allizwell.jobsdoor360.in

Hash Functions

Data Structures and Algorithms / Hashing / Hash Functions

Hash Functions

A hash function is a function that converts a key into a hash value. This value is used to determine the position where the key or its associated data should be stored in a hash table. A well-designed hash function distributes keys evenly across the table, reducing collisions and helping provide efficient insertion, searching, and deletion operations.

1. What Is a Hash Function?

A hash function takes a key as input and produces an integer value called a hash value. In a hash table, this value is usually converted into a valid table index.

For example, suppose a hash table contains 10 positions, numbered from 0 to 9. We can use the remainder operator to calculate an index.

h(key) = key % tableSize

If key = 42
and tableSize = 10

h(42) = 42 % 10
      = 2

Hash index = 2

Simple Example

Suppose we want to store the following keys:

12, 25, 33, 47, 58

Using the hash function h(key) = key % 10:

Key Calculation Index
12 12 % 10 2
25 25 % 10 5
33 33 % 10 3
47 47 % 10 7
58 58 % 10 8

2. Characteristics of a Good Hash Function

A good hash function should have the following characteristics.

1. Deterministic

The same key should produce the same hash value when the function is used with the same configuration.

h(25) = 5
h(25) = 5
h(25) = 5

2. Uniform Distribution

Keys should be distributed as evenly as possible across the available table positions.

If most keys map to only a few positions, those positions become crowded and collisions increase.

3. Efficient to Compute

A hash function should be quick to calculate. If hashing a key takes a long time, the benefit of fast lookup is reduced.

4. Minimize Collisions

A good hash function should reduce the number of collisions. However, collisions cannot always be avoided when many possible keys are mapped to a limited number of table positions.

Important: A hash function cannot guarantee that every key receives a unique index when the number of possible keys is larger than the number of table positions.

3. Division Method

The division method is one of the simplest methods for constructing a hash function.

It calculates the remainder when a key is divided by the table size.

h(key) = key % m

Where:
key = input key
m   = table size

Example

Table size = 7
Key = 45

h(45) = 45 % 7
      = 3

Index = 3

Another key, 52, produces the same index:

h(52) = 52 % 7
      = 3

This is a collision because both keys map to index 3.

C++ Example

#include <iostream>
using namespace std;

int hashFunction(int key, int tableSize) {
    return key % tableSize;
}

int main() {

    int key = 45;
    int tableSize = 7;

    cout << "Hash index: "
         << hashFunction(key, tableSize);

    return 0;
}

Output

Hash index: 3

When choosing a table size for a simple division-based hash function, a prime number is often a useful choice. It can help avoid some undesirable patterns in key distributions, although it does not guarantee a collision-free table.

4. Multiplication Method

The multiplication method uses multiplication by a constant and extracts a portion of the resulting value to calculate the hash index.

One common form is:

h(key) = floor(m * fractional_part(key * A))

Where:
m = table size
A = constant between 0 and 1
fractional_part(x) = x - floor(x)

Example

Suppose:

key = 25
m = 10
A = 0.6

key * A = 25 * 0.6
        = 15

Fractional part of 15 = 0

h(25) = floor(10 * 0)
      = 0

This example demonstrates the calculation, but the chosen constant is not necessarily a good choice for all keys. The quality of the distribution depends on the constant and the input values.

5. Folding Method

The folding method divides a large key into smaller parts. These parts are then added together to produce a hash value.

Example

Key = 123456789

Divide into groups:

123 + 456 + 789

Sum = 1368

For table size 100:

h(key) = 1368 % 100
       = 68

The resulting index is 68.

Folding can be useful when keys contain several digits, such as identification numbers or account numbers.

6. Mid-Square Method

In the mid-square method, the key is squared and a portion of the middle digits is selected to form the hash value.

Example

Key = 44

Square the key:

44 * 44 = 1936

Choose the middle two digits:

93

For table size 100:

Hash index = 93

The exact number of digits selected depends on the table size. For example, a table with 100 positions requires an index from 0 to 99.

7. Comparing Hash Function Methods

Method Basic Idea Example Use
Division Use the remainder of key divided by table size. Integer keys
Multiplication Multiply by a constant and use the fractional part. Integer key distribution
Folding Divide the key into parts and add them. Long numeric identifiers
Mid-Square Square the key and extract middle digits. Numeric keys

8. Hash Functions for Strings

Hash functions can also process strings. One simple approach is to convert each character into its character code and combine those values.

For example, a string can be processed by adding the character codes of its letters.

String: "ABC"

Character codes:
A = 65
B = 66
C = 67

Sum = 65 + 66 + 67
    = 198

If the table size is 10:

Hash index = 198 % 10
           = 8
Limitation: A simple sum of character codes can produce the same result for different strings. For example, "ABC" and "CBA" have the same sum. More sophisticated string hash functions account for character positions and improve distribution.

C++ String Hash Example

#include <iostream>
#include <string>
using namespace std;

int simpleHash(string s, int tableSize) {

    int sum = 0;

    for (char ch : s) {
        sum += static_cast<unsigned char>(ch);
    }

    return sum % tableSize;
}

int main() {

    string word = "ABC";

    cout << "Hash index: "
         << simpleHash(word, 10);

    return 0;
}

Output

Hash index: 8

This is a basic educational example. In practical applications, string hashing should use a suitable hash function designed for the required performance and security properties.

9. Hash Function vs Cryptographic Hash Function

Hash functions used in hash tables and cryptographic hash functions have different goals.

Feature Hash Table Function Cryptographic Hash Function
Main Goal Efficient data lookup Security properties
Output Often a table index or hash value Fixed-length digest
Collision Requirement Reduce collisions for good performance Make finding collisions computationally difficult
Speed Usually very fast Designed according to security requirements
Examples Hash table key hashing SHA-256, SHA-3
Important: A hash function used for a hash table is not automatically secure for password storage. Password storage requires dedicated password-hashing algorithms such as Argon2id, scrypt, or bcrypt, with appropriate salts and parameters.

10. Hash Function and Collision

A collision occurs when two different keys produce the same hash index.

h(key) = key % 10

h(15) = 15 % 10 = 5

h(25) = 25 % 10 = 5

Both keys map to index 5.

A good hash function reduces the frequency of collisions, but a hash table still needs a collision-handling strategy.

Common strategies include:

  • Separate Chaining
  • Linear Probing
  • Quadratic Probing
  • Double Hashing

These techniques will be covered in the upcoming topics.

11. Time and Space Complexity

The time complexity of a hash function depends on the type of key and how the function is calculated.

Hash Function Typical Computation Cost
Integer Division Method O(1) for fixed-size integer keys
Multiplication Method O(1) for fixed-size integer keys
Folding Method Depends on the number of key digits
Mid-Square Method O(1) for fixed-size integer keys
String Hashing Usually O(L), where L is string length

A hash function generally uses O(1) auxiliary space when processing fixed-size integer keys. A string hash function may use O(1) auxiliary space while processing a string of length L, depending on its implementation.

12. Common Mistakes

  • Assuming no collisions: Different keys can produce the same index.
  • Choosing a poor hash function: Uneven distribution can increase collisions.
  • Ignoring table size: The calculated index must be valid for the hash table.
  • Confusing hash values and indices: A hash value may need to be reduced to a valid table index.
  • Assuming every hash function is secure: Ordinary hash table functions are not designed for cryptographic security.
  • Ignoring string length: Processing a string generally requires examining its characters.
  • Assuming prime table size solves all collisions: A prime table size may help distribution, but collisions can still occur.

13. Interview Questions

  1. What is a hash function?
  2. What are the characteristics of a good hash function?
  3. Explain the division method of hashing.
  4. What is the multiplication method?
  5. Explain the folding method with an example.
  6. What is the mid-square method?
  7. How can a hash function process strings?
  8. What is a collision?
  9. Can a hash function guarantee unique indices?
  10. Why is a prime table size often used in division-based hashing?
  11. What is the difference between a hash table function and a cryptographic hash function?
  12. What is the time complexity of hashing a string of length L?

14. Practice Problems

  1. Implement the division method for a hash function.
  2. Calculate hash values for a list of integer keys.
  3. Implement a simple string hash function.
  4. Use the folding method to calculate a hash index.
  5. Use the mid-square method to calculate a hash index.
  6. Identify collisions for a given hash function and list of keys.
  7. Compare two hash functions based on their key distributions.
  8. Design a hash function for a collection of student roll numbers.

15. Summary

  • A hash function converts a key into a hash value.
  • The hash value is used to determine a storage position in a hash table.
  • A good hash function should be deterministic, efficient, and distribute keys evenly.
  • The division method uses the remainder operator.
  • The multiplication method uses a constant and a fractional part.
  • The folding method divides a key into parts and combines them.
  • The mid-square method squares a key and extracts middle digits.
  • String hash functions combine character information to produce a hash value.
  • Collisions are possible even with a good hash function.
  • Hash table functions and cryptographic hash functions have different purposes.
Key Takeaway: A hash function is the foundation of hashing. Its job is to convert keys into useful hash values while distributing keys effectively. Understanding hash functions makes it easier to learn hash tables and collision handling.
Scroll to Top