You can use Sorting, Set or even Unordered Map to achieve your task.
- If you can alter the contents of the array, prefer sorting
- If you can't alter the contents of the array, set is a good choice
- If you can't alter the contents of the array & want to achieve
O(N) complexity prefer unordered map
Using sorting
// Checking duplicates with Sorting, Complexity: O(nlog(n))
bool checkDuplicatesWithSorting(int array[], int n)
{
sort(array, array+n);
for(int i = 1; i < n; i++ )
{
if(array[i]==array[i-1])
return true;
}
return false;
}
Using Set
// Checking duplicates with a Set, Complexity: O(nlog(n))
bool checkDuplicatesWithSet(int array[], int n)
{
set <int> s(array, array+n);
return s.size() != n;
}
Using Unordered Map
// Checking duplicates with a Unordered Map, Complexity: O(n) (Average Case)
bool checkDuplicatesWithHashMap(int array[], int n)
{
unordered_map<int, bool>uo_map;
for(int i=0;i<n;i++){
if(uo_map.find(array[i]) == uo_map.end())
uo_map[array[i]] = true;
else return true;
}
return false;
}
Live Code
log(n)suggests a binary search tree. Insert nodes one-by-one in a binary tree and if there is any duplicate while inserting, nodes are not distinct. Worst case complexity can still ben^2