Find Duplicate in Array

Easy
0/40
Average time to solve is 15m
970 upvotes
Asked in companies
OlaAmazonBNY Mellon

Problem statement

You are given an array of integers 'ARR' containing N elements. Each integer is in the range [1, N-1], with exactly one element repeated in the array.

Your task is to find the duplicate element. The duplicate element may be repeated more than twice in the error, but there will be exactly one element that is repeated in the array.

Note :

All the integers in the array appear only once except for precisely one integer which appears two or more times.
Detailed explanation ( Input/output format, Notes, Images )

Input format:

The first line of input contains an integer ‘T’ denoting the number of test cases. Then the T test cases follow.

The first line of each test case contains an integer ‘N’, the number of elements in the array. 

The second line of each test case contains ‘N’ space-separated integers representing the elements of the array. 

Output format:

For each test case, the duplicate element of the given array is printed.

The output of each test case is printed in a separate line. 
Note :
You are not supposed to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
1 <= N <= 10^5
1 <= ARR[i] <= N - 1

Time Limit: 1 sec

Sample Input 1:

1
3
1 1 2

Sample Output 1:

1

Explanation of Sample Input 1:

1 is repeated in the array, hence function returns 1.

Sample Input 2:

3
5
1 3 4 2 2
5
3 1 3 4 2
3
1 1 1

Sample Output 2:

2
3
1
Hint

If the array is sorted, then the repeated elements will be adjacent to each other in the sorted array.

Approaches (5)
Using Sort

First, we sort the array. Now, the rest of the algorithm becomes fairly simple. We just compare each element to its previous element. As we know there is exactly one repeated element, hence we can simply just return the element, which is equal to its previous element as soon as we find it.

Time Complexity

O(N * log(N)), where N is the length of the array.

 

The sorting of elements costs O(N * log(N)) time, which dominates the subsequent linear scan.

Space Complexity

O(1) or O(N),

 

We can sort the array either in place or by taking another array if modifying the given array is not permitted. Here we suppose that modifying the array is possible, hence using constant space makes space complexity = O(1).

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Find Duplicate in Array
Full screen
Console