C++ code to find index where this is a hash collision

Suppose we have a number p and another array X with n elements. There is a hash table with p buckets. The buckets are numbered from 0 to p-1. We want to insert n numbers from X. We are assuming for X[i], its bucket will be selected by the hash function h(X[i]), where h(k) = k mod p. One bucket cannot hold more than one element. If We want to insert an number into a bucket which is already filled, we say a "collision" happens. We have to return the index where collision has happened. If there is no collision, return -1.

So, if the input is like p = 10; X = [0, 21, 53, 41, 53], then the output will be 3, because first one will be inserted into 0, second one at 1, third one at 3, but 4th one will try to insert into 1 but there is a collision, the index is 3 here.

Steps

To solve this, we will follow these steps −

n := size of X
Define an array arr of size: p and fill with 0
for initialize i := 0, when i 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;
int solve(int p, vector X){
   int n = X.size();
   int arr[p] = { 0 };
   for (int i = 0; i  X = { 0, 21, 53, 41, 53 };
   cout 

Input

10, { 0, 21, 53, 41, 53 }

Output

3
Updated on: 2022-03-30T13:05:42+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements