VOOZH about

URL: https://www.geeksforgeeks.org/dsa/quadratic-probing-in-hashing/

⇱ Quadratic Probing in Hashing - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Quadratic Probing in Hashing

Last Updated : 7 Jul, 2025

Hashing is an improvement technique over the Direct Access Table. The idea is to use a hash function that converts a given number or any other key to a smaller number and uses the small number as the index in a table called a hash table

Quadratic Probing:

Quadratic probing is an open-addressing scheme where we look for the i2'th slot in the i'th iteration if the given hash value x collides in the hash table. We have already discussed linear probing implementation.

How Quadratic Probing is done?

Let hash(x) be the slot index computed using the hash function.

  • If the slot hash(x) % S is full, then we try (hash(x) + 1*1) % S.
  • If (hash(x) + 1*1) % S is also full, then we try (hash(x) + 2*2) % S.
  • If (hash(x) + 2*2) % S is also full, then we try (hash(x) + 3*3) % S.
  • This process is repeated for all the values of i until an empty slot is found.

Example:
Let us consider a simple hash function as “key mod 7” and  sequence of keys as 22, 30 and 50.


Below is the implementation of the above approach:


Output
73 -1 101 -1 92 -1 50 700 85 -1 76 

Time Complexity: O(n * l), where n is the length of the array and l is the size of the hash table.
Auxiliary Space: O(1)

The above implementation of quadratic probing does not guarantee that we will always be able to use a hash table empty slot. It might happen that some entries do not get a slot even if there is a slot available.
Let's consider the input array [21, 10, 32, 43, 54, 65, 87, 76] and table size 11, we get the output as [10, -1, 65, 32, 54, -1, -1, -1, 43, -1, 21] which means the items 87 and 76 never get a slot. To make sure that elements get filled, we need to have a higher table size.

A hash table can be fully utilized using the below idea.

Iterate over the hash table to next power of 2 of table size. For example if table size is 11, then iterate 16 times. And iterate over the hash table using the below formula

hash(x) = [hash(x) + (j + j*j)/2] % (Next power of 2 of table size)


Output
10 87 -1 -1 32 -1 54 65 76 43 21 

Time Complexity: O(n * l), where n is the length of the array and l is the size of the hash table.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: