# Find duplicates in a given array when elements are not limited to a range

Given an array of n integers. The task is to print the duplicates in the given array. If there are no duplicates then print -1.

Examples:

```Input : {2, 10, 100, 2, 10, 11}
Output : 2 10

Input : {5, 40, 1, 40, 100000, 1, 5, 1}
Output : 5 40 1
```

Note:The duplicate elements can be printed in any order.

Simple Approach: By using two loops. It has a time complexity of O(n2).

Efficient Approach: Use unordered_map for hashing. Count frequency of occurrence of each element and the elements with frequency more than 1 is printed. unordered_map is used as range of integers is not known.

`// C++ program to find`
`// duplicates in the given array`
`#include <bits/stdc++.h>`
`using` `namespace` `std;`
`// function to find and print duplicates`
`void` `printDuplicates(``int` `arr[], ``int` `n)`
`{`
`    ``// unordered_map to store frequencies`
`    ``unordered_map<``int``, ``int``> freq;`
`    ``for` `(``int` `i=0; i<n; i++)`
`        ``freq[arr[i]]++;`
`    ``bool` `dup = ``false``;`
`    ``unordered_map<``int``, ``int``>:: iterator itr;`
`    ``for` `(itr=freq.begin(); itr!=freq.end(); itr++)`
`    ``{`
`        ``// if frequency is more than 1`
`        ``// print the element`
`        ``if` `(itr->second > 1)`
`        ``{`
`            ``cout << itr->first << ``" "``;`
`            ``dup = ``true``;`
`        ``}`
`    ``}`
`    ``// no duplicates present`
`    ``if` `(dup == ``false``)`
`        ``cout << ``"-1"``;`
`}`
`// Driver program to test above`
`int` `main()`
`{`
`    ``int` `arr[] = {12, 11, 40, 12, 5, 6, 5, 12, 11};`
`    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);`
`    ``printDuplicates(arr, n);`
`    ``return` `0;`
`}`

Output:

```12 11 5
```

Time Complexity: O(n)

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh