Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does array length plays any role while finding a repeated element in array list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your solution is based on assumption that your array must contain

  • all numbers from 0 till "some" N, like 0, 1, 2, 3, .. , N (in any order)
  • and one extra element X.

How many elements are there?

  • 0 ... N gives us N+1 elements
  • X is 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading