public static int findDuplicate(int[] arr) {
int n = arr.length-2;
int sum = 0;
for(int i : arr){
sum+=i;
}
return (sum - ((n*(n+1))/2));
}
Here is the code. This code must return any duplicate element present in the array. Say, if array is { 1, 2, 3, 4, 1 } then it must return 1. It works fine for the test cases but I just want to understand the role of arr.length-2 used here.
Sample input
5 size
1 2 3 4 1
Sample output :
1
>Solution :
Your solution is based on assumption that your array must contain
- all numbers from
0till "some"N, like0, 1, 2, 3, .. , N(in any order) - and one extra element
X.
How many elements are there?
0 ... Ngives usN+1elementsXis 1 element.
So we have N+1 + 1 which is N+2 element.
In other words array has N+2 elements, which means N+2 = array.length. And that means
N = array.length - 2.
Now sum of all array elements is 0 + 1 + 2 + ... + N + X (their order doesn’t matter for calculating sum).
We can get rid of 0 since it doesn’t affect our sum so 0 + 1 + 2 + ... + N becomes 1 + 2 + ... + N which leaves us with
SUM = 1 + 2 + ... + N + X
and here we can also replace 1 + 2 + ... + N with N*(N+1)/2 based on formula on sum of arithmetic series which gives us
SUM = N*(N+1)/2 + X
Based on above the duplicate element X is X = SUM - N*(N+1)/2 where N = array.length-2.