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

C++Server Side ProgrammingProgramming

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.


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 < n, update (increase i by 1), do:
   x := X[i]
   if arr[x mod p] is non-zero, then:
      return i
   increase arr[x mod p] by 1
return -1


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int p, vector<int> X){
   int n = X.size();
   int arr[p] = { 0 };
   for (int i = 0; i < n; i++){
      int x = X[i];
      if (arr[x % p]){
         return i;
      arr[x % p]++;
   return -1;
int main(){
   int p = 10;
   vector<int> X = { 0, 21, 53, 41, 53 };
   cout << solve(p, X) << endl;


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


Updated on 30-Mar-2022 13:05:42