Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of the formula how to find lost element in array?

Tags:

java

algorithm

The task is to find lost element in the array. I understand the logic of the solution but I don't understand how does this formula works?

Here is the solution

int[] array = new int[]{4,1,2,3,5,8,6};
   int size = array.length;
   int result = (size + 1) * (size + 2)/2;
   for (int i : array){
       result -= i;
   }

But why we add 1 to total size and multiply it to total size + 2 /2 ?? In all resources, people just use that formula but nobody explains how that formula works

like image 476
Boris Ruzanov Avatar asked Dec 07 '22 10:12

Boris Ruzanov


1 Answers

The sum of the digits 1 thru n is equal to ((n)(n+1))/2.

e.g. for 1,2,3,4,5 5*6/2 = 15.

But this is just a quick way to add up the numbers from 1 to n. Here is what is really going on.

The series computes the sum of 1 to n assuming they all were present. But by subtracting each number from that sum, the remainder is the missing number.

The formula for an arithmetic series of integers from k to n where adjacent elements differ by 1 is.

S[k,n] = (n-k+1)(n+k)/2

Example: k = 5, n = 10

  • S[k,n] = 5 6 7 8 9 10

  • S[k,n] = 10 9 8 7 6 5

  • S[k,n] = (10-5+1)*(10+5)/2

  • 2S[k,n] = 6 * 15 / 2

  • S[k,n] = 90 / 2 = 45

For any single number missing from the sequence, by subtracting the others from the sum of 45, the remainder will be the missing number.

like image 51
WJS Avatar answered Jan 05 '23 00:01

WJS