You have been given an integer array/list(ARR) of size N which contains numbers from 0 to (N - 2). Each number is present at least once. That is, if N = 5, the array/list constitutes values ranging from 0 to 3 and among these, there is a single integer value that is present twice. You need to find and return that duplicate number present in the array.
Answers
Answer:
#include <iostream>
using namespace std;
int findUnique(int *arr, int size)
{
int res = arr[0];
for (int i = 1; i < size; i++)
res = res ^ arr[i];
return res;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *input = new int[size];
for (int i = 0; i < size; ++i)
{
cin >> input[i];
}
cout << findUnique(input, size) << endl;
}
return 0;
}
Explanation:
Answer:
public static int findDuplicate(int[] arr) {
int sum=0;
for(int i=0;i<=arr.length-2;i++)
{
sum=sum+i;
}
int n=0;
for(int i=0;i<arr.length;i++)
{
n=n+arr[i];
}
int x=n-sum;
return x;
}
Explanation:
subtract the total sum of elements in the array -the sum of the numbers ranging from 0 to n-2