The Wayback Machine - https://web.archive.org/web/20240907013133/https://www.geeksforgeeks.org/what-are-hash-functions-and-how-to-choose-a-good-hash-function/
Open In App

What are Hash Functions and How to choose a good Hash Function?

Last Updated : 21 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
83.07%
1.4K

Prerequisite: Hashing | Set 1 (Introduction) 

What is a Hash Function? 

A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. 

What is meant by Good Hash Function? 

A good hash function should have the following properties: 

  1. Efficiently computable.
  2. Should uniformly distribute the keys (Each table position equally likely for each key)

For example: For phone numbers, a bad hash function is to take the first three digits. A better function is considered the last three digits. Please note that this may not be the best hash function. There may be better ways. 

Rules for choosing good hash function:

1. The hash function should be simple to compute.

2. Number of collisions should be less while placing the record in the hash table.Ideally no collision should occur. Such a function is called perfect hash function.

3. Hash function should produce such keys which will get distributed uniformly over an array.

4. The hash function should depend on every bit of the key. Thus the hash function that simply extracts the portion of a key is not suitable.

In practice, we can often employ heuristic techniques to create a hash function that performs well. Qualitative information about the distribution of the keys may be useful in this design process. In general, a hash function should depend on every single bit of the key, so that two keys that differ in only one bit or one group of bits (regardless of whether the group is at the beginning, end, or middle of the key or present throughout the key) hash into different values. Thus, a hash function that simply extracts a portion of a key is not suitable. Similarly, if two keys are simply digited or character permutations of each other (such as 139 and 319), they should also hash into different values. 

The two heuristic methods are hashing by division and hashing by multiplication which are as follows: 

  1. The mod method: 
    • In this method for creating hash functions, we map a key into one of the slots of table by taking the remainder of key divided by table_size. That is, the hash function is 
       
h(key) = key mod table_size 

i.e. key % table_size
  • Since it requires only a single division operation, hashing by division is quite fast.
  • When using the division method, we usually avoid certain values of table_size like table_size should not be a power of a number suppose r, since if table_size = r^p, then h(key) is just the p lowest-order bits of key. Unless we know that all low-order p-bit patterns are equally likely, we are better off designing the hash function to depend on all the bits of the key.
  • It has been found that the best results with the division method are achieved when the table size is prime. However, even if table_size is prime, an additional restriction is called for. If r is the number of possible character codes on an computer, and if table_size is a prime such that r % table_size equal 1, then hash function h(key) = key % table_size is simply the sum of the binary representation of the characters in the key mod table_size.
  • Suppose r = 256 and table_size = 17, in which r % table_size i.e. 256 % 17 = 1.
  • So for key = 37599, its hash is 
     
37599 % 17 = 12
  • But for key = 573, its hash function is also
573 % 17 = 12
  • Hence it can be seen that by this hash function, many keys can have the same hash. This is called Collision.
  • A prime not too close to an exact power of 2 is often good choice for table_size.
  1. The multiplication method: 
    • In multiplication method, we multiply the key k by a constant real number c in the range 0 < c < 1 and extract the fractional part of k * c.
    • Then we multiply this value by table_size m and take the floor of the result. It can be represented as
h(k) = floor (m * (k * c mod 1))
                     or
h(k) = floor (m * frac (k * c))
  • where the function floor(x), available in standard library math.h, yields the integer part of the real number x, and frac(x) yields the fractional part. [frac(x) = x – floor(x)] 
     
  • An advantage of the multiplication method is that the value of m is not critical, we typically choose it to be a power of 2 (m = 2p for some integer p), since we can then easily implement the function on most computers
  • Suppose that the word size of the machine is w bits and that key fits into a single word.
  • We restrict c to be a fraction of the form s / (2w), where s is an integer in the range 0 < s < 2w. 
     
  • Referring to figure, we first multiply key by the w-bit integer s = c * 2w. The result is a 2w-bit value
r1 * 2w + r0

where r1 = high-order word of the product
      r0 = lower order word of the product
  • Although this method works with any value of the constant c, it works better with some values than the others.
c ~ (sqrt (5) – 1) / 2 = 0.618033988 . . .
  • is likely to work reasonably well.
  • Suppose k = 123456, p = 14,
  • m = 2^14 = 16384, and w = 32.
  • Adapting Knuth’s suggestion, c to be fraction of the form s / 2^32.
  • Then key * s = 327706022297664 = (76300 * 2^32) + 17612864,
  • So r1 = 76300 and r0 = 176122864.
  • The 14 most significant bits of r0 yield the value h(key) = 67.


Similar Reads

Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Count of Ways to Choose N People With at Least X Men and Y Women from P Men and Q Women | Set 2
Given integers N, P, Q, X, and Y, the task is to find the number of ways to form a group of N people having at least X men and Y women from P men and Q women, where (X + Y â‰Ī N, X â‰Ī P and Y â‰Ī Q). Examples: Input: P = 4, Q = 2, N = 5, X = 3, Y = 1Output: 6Explanation: Suppose given pool is {m1, m2, m3, m4} and {w1, w2}. Then possible combinations are
7 min read
Count of ways to choose N people containing at least 4 boys and 1 girl from P boys and Q girls
Given integers N, P, and Q the task is to find the number of ways to form a group of N people having at least 4 boys and 1 girls from P boys and Q girls. Examples: Input: P = 5, Q = 2, N = 5Output: 10Explanation: Suppose given pool is {m1, m2, m3, m4, m5} and {w1, w2}. Then possible combinations are: m1 m2 m3 m4 w1m2 m3 m4 m5 w1m1 m3 m4 m5 w1m1 m2
6 min read
Count of All Possible Ways to Choose N People With at Least X Men and Y Women from P Men and Q Women
Given integers N, P, Q, X, and Y, the task is to find the number of ways to form a group of N people having at least X men and Y women from P men and Q women, where (X + Y â‰Ī N, X â‰Ī P and Y â‰Ī Q). Examples: Input: P = 4, Q = 2, N = 5, X = 3, Y = 1Output: 6Explanation: Suppose given pool is {m1, m2, m3, m4} and {w1, w2}. Then possible combinations are
7 min read
Count of Ways to Choose N People Containing at Least 4 Boys and 1 Girl from P Boys and Q Girls | Set 2
Given integers N, P, and Q the task is to find the number of ways to form a group of N people having at least 4 boys and 1 girl from P boys and Q girls. Examples: Input: P = 5, Q = 2, N = 5Output: 10Explanation: Suppose given pool is {m1, m2, m3, m4, m5} and {w1, w2}. Then possible combinations are:m1 m2 m3 m4 w1m2 m3 m4 m5 w1m1 m3 m4 m5 w1m1 m2 m4
7 min read
Number of ways to choose a pair containing an even and an odd number from 1 to N
Given a number N the task is to find the number of pairs containing an even and an odd number from numbers between 1 and N inclusive. Note: The order of numbers in the pair does not matter. That is (1, 2) and (2, 1) are the same. Examples: Input: N = 3 Output: 2 The pairs are (1, 2) and (2, 3).Input: N = 6 Output: 9 The pairs are (1, 2), (1, 4), (1
3 min read
Choose atleast two elements from array such that their GCD is 1 and cost is minimum
Given two integer arrays arr[] and cost[] where cost[i] is the cost of choosing arr[i]. The task is to choose a subset with at least two elements such that the GCD of all the elements from the subset is 1 and the cost of choosing those elements is as minimum as possible then print the minimum cost. Examples: Input: arr[] = {5, 10, 12, 1}, cost[] =
6 min read
Choose X elements from A[] and Y elements from B[] which satisfy the given condition
Given two arrays A[] and B[] and two integers X and Y, the task is to choose X elements from A[] and Y elements from B[] such that all the chosen elements from A[] are less than all the chosen elements from B[]Examples: Input: A[] = {1, 1, 1, 1, 1}, B[] = {3, 1}, X = 3, Y = 1 Output: Yes Choose {1, 1, 1} from A[] and {3} from B[].Input: A[] = {5, 4
5 min read
Choose k array elements such that difference of maximum and minimum is minimized
Given an array of n integers and a positive number k. We are allowed to take any k integers from the given array. The task is to find the minimum possible value of the difference between maximum and minimum of K numbers. Examples: Input : arr[] = {10, 100, 300, 200, 1000, 20, 30} k = 3 Output : 20 20 is the minimum possible difference between any m
5 min read
Choose maximum weight with given weight and value ratio
Given weights and values of n items and a value k. We need to choose a subset of these items in such a way that ratio of the sum of weight and sum of values of chosen items is K and sum of weight is maximum among all possible subset choices. Input : weight[] = [4, 8, 9] values[] = [2, 4, 6] K = 2 Output : 12 We can choose only first and second item
9 min read
Counting Good stones in a river with positive and negative steps
Geek is in a geekland which has a river and some stones in it. Initially, a geek can step on any stone. Each stone has a number on it representing the value of the exact step the geek can move. If the number is +ve then geeks can move right and if the number is -ve then geeks can move left. Bad Stones are defined as stones that if geeks steps, will
15+ min read
How can one become good at Data structures and Algorithms easily?
Let us first clarify the question. There is not any easy way to become good at anything but there is an efficient way to do everything. Let us try to understand the difference between easy and efficient here with the help of a programming question! Consider the problem of "Searching an element in a sorted array". Person A solves the above problem b
4 min read
Sorting using trivial hash function
We have read about various sorting algorithms such as heap sort, bubble sort, merge sort and others. Here we will see how can we sort N elements using a hash array. But this algorithm has a limitation. We can sort only those N elements, where the value of elements is not large (typically not above 10^6). Examples: Input : 9 4 3 5 8 Output : 3 4 5 8
15+ min read
Classify strings from an array using Custom Hash Function
Given an array of strings arr[] consisting of N strings, the task is to categorize the strings according to the hash value obtained by adding ASCII values % 26 of the characters in the string. Examples: Input: arr[][] = {"geeks", "for", "geeks"}Output:geeks geeksforExplanation:The hash value of string "for" is (102 + 111 + 114) % 26 = 14The hash va
8 min read
Minimum operations to choose Array elements with sum as K by choosing element from front, or rear or both
Given an array arr[] of positive integers of size N, and an integer K. The task is to minimize the number of operations required choose array elements that sum up to K. In one operation, an element can be removed either from the front, or from the rear, or from both front and rear, and added to the sum. If the desired sum can't be achieved, return
14 min read
Ways to choose three points with distance between the most distant points &lt;= L
Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to L Note: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points Exam
15+ min read
Choose n elements such that their mean is maximum
Given an array of 2 * n elements, the task is to construct and print an array of n elements such that the mean of the new array is maximum. Here n is even. Examples: Input: arr[] = {3, 1, 2, 3, 8, 6} Output: 3 6 8 Input: arr[] = {3, 2, 3, 8} Output: 3 8 Approach: Mean of an array is the average of the elements of the same array i.e (?arr[i]) / n. S
10 min read
Count of ways to choose an integer that has exactly K larger elements in Array
Given an array arr[] of N distinct integers and a positive integer K, the task is to find the number of ways of choosing an integer X such that there are exactly K elements in the array that are greater than X. Examples: Input: arr[] = {1, 3, 4, 6, 8}, K = 2 Output: 3Explanation: X can be chosen as 4 or 5 Input: arr[] = {1, 2, 3}, K = 1 Output: 2Ex
9 min read
Number of ways to choose elements from the array such that their average is K
Given an array arr[] of N integers and an integer K. The task is to find the number of ways to select one or more elements from the array such that the average of the selected integers is equal to the given number K. Examples: Input: arr[] = {7, 9, 8, 9}, K = 8 Output: 5 {8}, {7, 9}, {7, 9}, {7, 8, 9} and {7, 8, 9}Input: arr[] = {3, 6, 2, 8, 7, 6,
11 min read
Ways to choose balls such that at least one ball is chosen
Given an integer N, the task is to find the ways to choose some balls out of the given N balls such that at least one ball is chosen. Since the value can be large so print the value modulo 1000000007.Example: Input: N = 2 Output: 3 The three ways are "*.", ".*" and "**" where '*' denotes the chosen ball and '.' denotes the ball which didn't get cho
3 min read
Choose two elements from the given array such that their sum is not present in any of the arrays
Given two arrays A[] and B[], the task is to choose two elements X and Y such that X belongs to A[] and Y belongs to B[] and (X + Y) must not be present in any of the array.Examples: Input: A[] = {3, 2, 2}, B[] = {1, 5, 7, 7, 9} Output: 3 9 3 + 9 = 12 and 12 is not present in any of the given arrays.Input: A[] = {1, 3, 5, 7}, B[] = {7, 5, 3, 1} Out
5 min read
Find if it is possible to choose subarray that it contains exactly K even integers
Given 2 positive integers N and K and an array arr[], the task is to find whether it is possible to choose a non-empty subarray of the array such that the subarray contains exactly K even integers. Examples: Input: N = 4, K = 2, arr[] = {1, 2, 4, 5} Output: Yes Explanation: We can select the subarray {2, 4} which contains exactly K = 2 even numbers
7 min read
Choose an integer K such that maximum of the xor values of K with all Array elements is minimized
Given an array A consisting of N non-negative integers, the task is to choose an integer K such that the maximum of the xor values of K with all array elements is minimized. In other words find the minimum possible value of Z, where Z = max(A[i] xor K), 0 &lt;= i &lt;= n-1, for some value of K. Examples: Input: A = [1, 2, 3] Output: 2 Explanation:
7 min read
Number of ways to choose K intersecting line segments on X-axis
Given an array arr[] of line segments on the x-axis and an integer K, the task is to calculate the number of ways to choose the K line-segments such that they do intersect at any point. Since the answer can be large, print it to modulo 10^9+7. Examples: Input: arr[] = [[1, 3], [4, 5], [5, 7]], K = 2 Output: 2 Explanation: The first way to choose [1
10 min read
Puzzle | Choose the game of Rolling Dice
Puzzle: You are risk-averse person. There are Two games are offered to you. Game 1: You roll a dice once and you are paid one trillion times the number of dots on the upturned face of the dice.Game 2: You roll a dice one trillion times. For each roll, you are paid Rs 1 times the number of dots on the upturned face of the dice. Which game do you pre
1 min read
Count of ways to choose K elements from given Array with maximum sum
Given an array, arr[] of size N and an integer K, the task is to find the number of ways of selecting K array elements, such that the sum of these K elements is the maximum possible sum. Examples: Input: arr[] = {3, 1, 1, 2}, K = 3 Output: 2Explanation: The possible ways of selecting 3 elements are: {arr[0] (=3), arr[1] (=1), arr[2] (=1)}, the sum
8 min read
Count ways to choose Triplets of Pairs such that either first or second values are distinct
Given an array of pairs arr[] of size N (N ? 3) where each element of pair is at most N and each pair is unique, the task is to determine the number of ways to select triplets from the given N pairs that satisfy at least one of the following conditions: The first value (a) of each pair should be distinct.The second value (b) of each pair should be
7 min read
Count ways to choose elements from given Arrays
Given arrays A[] and B[] of size N, the task is to count ways to form an array of size N such that the new array formed has ith element either A[i] or B[i] and adjacent elements are different. Examples: Input: A[] = {1, 4, 3}, B[] = {2, 2, 4}Output: 4Explanation: Possible arrays are {1, 4, 3}, {1, 2, 3}, {1, 2, 4} and {2, 4, 3}.Below is the Recursi
11 min read
Count of ways to choose 4 unique position elements one from each Array to make sum at most K
Given four arrays A[], B[], C[], D[] and an integer K. The task is to find the number of combinations of four unique indices p, q, r, s such that A[p] + B[q] + C[r] + D[s] â‰Ī K. Examples: Input: A = {2, 3}, B = {5, 2}, C = {0}, D = {1, 2}, K = 6Output: 3Explanation: The following are the required combinations:{2, 2, 0, 1}, {2, 2, 0, 2}, {3, 2, 0, 1}
13 min read
Choose X such that (A xor X) + (B xor X) is minimized
Given two integers A and B. The task is to choose an integer X such that (A xor X) + (B xor X) is the minimum possible. Examples: Input: A = 2, B = 3 Output: X = 2, Sum = 1 Input: A = 7, B = 8 Output: X = 0, Sum = 15 A simple solution is to generate all possible sum by taking xor of A and B with all possible values of X ? min(A, B). To generate all
9 min read
Article Tags :
Practice Tags :