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.
Input Format:
The first line of input contains an integer ‘T’ denoting the number of test cases. Then the T test cases follow.
The second line of each test case contains an integer ’N’, the number of elements in the array.
The third 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.
Given:
1
3
1 1 2
Output:
1
Constraints:
1 <= T <= 51 <= N <= 10^51 <= ARR[i] <= N — 1Time Limit: 1 sec
Explanation of given Test Cases :
1 is repeated in the array, hence function returns 1.
Approach:
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 print the element, which is equal to its previous element as soon as we find it.
Code:
Time Complexity: O(N*log(N))
Space Complexity: O(1)