Last active
February 24, 2021 19:53
-
-
Save hiteshchopra11/e810d934690260d3c8ad602e13fe65cd to your computer and use it in GitHub Desktop.
Duplicate number using hashing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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