This post will discuss how to check for duplicates in an array in C++.

1. Using Set

A simple and elegant solution is to construct a set from the array which retains only distinct elements. Then simply compare the set’s size against the array’s length. If both are not the same, then we can say that the array contains duplicates. This works in linear time and space.

Download  Run Code

Output:

Array contains duplicates

2. Using Sorting

Another option is to sort the array and compare each pair of consecutive elements to check for duplicates. This works in O(nlog(n)) time if the standard sorting algorithm is used. This would translate to the following code:

Download  Run Code

Output:

Array contains duplicates

3. Using std::adjacent_find

A better solution is to use std::adjacent_find to find the first occurrence of equal adjacent elements in the sorted array. It returns an iterator to the first duplicate elegant, or end of the range if no duplicate is found.

Download  Run Code

Output:

Array contains duplicates

 
With C++11, we can get an iterator to the beginning and end of the array:

Download  Run Code

Output:

Array contains duplicates

4. Using std::unique function

Alternatively, we can use the std::unique function to remove consecutive duplicates after sorting the array. It can be used as follows:

Download  Run Code

Output:

Array contains duplicates

 
With C++11, we can get an iterator to the beginning and end of the array:

Download  Run Code

Output:

Array contains duplicates

That’s all about checking for duplicates in an array in C++.