Problem of the day
You are given an array ‘ARR’ of size ‘N’ containing each number between 1 and ‘N’ - 1 at least once. There is a single integer value that is present in the array twice. Your task is to find the duplicate integer value present in the array.
For example:
Consider ARR = [1, 2, 3, 4, 4], the duplicate integer value present in the array is 4. Hence, the answer is 4 in this case.
Note :
A duplicate number is always present in the given array.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains a single integer, 'N', denoting the number of elements in the array.
The second line of each test case contains 'N' space-separated integers denoting the elements of the array 'ARR'.
Output Format:
For each test case, print a single integer - the duplicate element in the array.
Print the output of each test case in a separate line.
1 <= T <= 10
2 <= N <= 10 ^ 5
1 <= ARR[i] <= N - 1
Where 'T' denotes the number of test cases, 'N' denotes the number of elements in the array, and 'ARR[i]' denotes the 'i-th' element of the array 'ARR'.
Time limit: 1 sec
2
5
4 2 1 3 1
7
6 3 1 5 4 3 2
1
3
For the first test case,
The duplicate integer value present in the array is 1. Hence, the answer is 1 in this case.
For the second test case,
The duplicate integer value present in the array is 3. Hence, the answer is 3 in this case.
2
6
5 1 2 3 4 2
9
8 7 2 5 4 7 1 3 6
2
7
1. Simply calculate the frequency of each value.
2. Try to optimise the above approach by using an array to store the frequencies.
3. Think of a solution using Floyd’s cycle finding algorithm.
4. Try to think of a solution based on bitwise XOR.
A simple method is to traverse through the array ARR to find the frequency of each number in the given array, and we will check if the frequency of the number is more than 1.
Therefore, our approach will be to iterate currentNumber from 1 to N - 1. In each iteration, we will traverse through the array ARR to find the frequency of currentNumber in the array. We will check if the frequency is more than 1, then there is a duplicate of the number currentNumber in the array ARR. In the end, we will return the duplicate integer value present in the array.
Algorithm:
O(N ^ 2), where N denotes the number of elements in the array.
We are doing N - 1 iteration, and in each iteration, we are traversing through the array ARR to find the frequency of the number in the given array that takes O(N) time. Hence, the overall Time Complexity = O(N) * (N) = O(N ^ 2).
O(1).
Constant space is being used. Hence, the overall Space Complexity is O(1).