Skip to content

Instantly share code, notes, and snippets.

@hiteshchopra11
Last active February 24, 2021 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiteshchopra11/e810d934690260d3c8ad602e13fe65cd to your computer and use it in GitHub Desktop.
Save hiteshchopra11/e810d934690260d3c8ad602e13fe65cd to your computer and use it in GitHub Desktop.
Duplicate number using hashing
#include <bits./stdc++.h>
using namespace std;
int duplicate_hashing(int arr[], int n)
{
//Create a boolean value of size n
bool flag[n];
//Set all values of flag boolean array initially as false
fill(flag, flag + n, false);
for (int i = 0; i < n; i++)
{
// If the element is present before, return that element
if (flag[arr[i]])
return arr[i];
// Set flag of visited element to true
flag[arr[i]] = true;
}
// No duplicate found so return 1
return -1;
}
int main()
{
//Declare array with one duplicate element
int arr[5] = {1, 2, 4, 4, 5};
//Calculate the size of array
int n = sizeof(arr) / sizeof(arr[0]);
//Find out either the duplicate element present in the array or -1
int duplicate = duplicate_hashing(arr, n);
//Print duplicate array element
cout << duplicate;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment