Define hash function. Explain it with suitable example.

Data Structure

A hash function is a function that takes an input (or "message") of any size and maps it to a
fixed-size value, which is typically a number. The result of this mapping is called a hash value
or hash code. Hash functions are commonly used in data structures such as hash tables to
quickly locate data records.

Working of a Hash Function:
● The hash function transforms input data into a hash value.
● The input can be any kind of data such as strings, numbers, or even objects.
● The output, or hash value, is usually of a fixed length (for example, a 32-bit or 64-bit
number), regardless of the size or type of the input data.

Example of a Hash Function:
Let’s consider a hash function that takes a book title as input. Suppose the input is the string
"Harry Potter".
● A simple hash function might take the ASCII values of each character in the string and
then sum them. For example, "H" (ASCII 72) + "a" (ASCII 97) + "r" (ASCII 114) + "r"
(ASCII 114) + and so on.
● The sum of all these ASCII values might result in a large number, say 2025, which will be
the hash value for "Harry Potter".
● In this case, the hash value 2025 is used to quickly locate the book in a list or database.

Properties of a Good Hash Function:

1. Deterministic: A good hash function must always produce the same hash value for the
same input. For example, if you apply the hash function to "Harry Potter" today, it should
give the same result 2025 as it would in the future.
2. Uniform Distribution: A good hash function should produce hash values that are
spread evenly across the range of possible outputs. This helps avoid situations where
many inputs map to the same hash value, which can cause inefficiencies and slowdowns
in searching.

Real-World Applications of Hash Functions:

● Hash Tables: Hash functions are commonly used in hash tables to store and retrieve
data efficiently. The hash value is used as an index to store or retrieve data in constant
time (on average).
● Digital Signatures: Hash functions are also used in cryptography to generate digital
signatures, which verify the integrity of data without exposing the original information.