Finding a missing number of a given arithmetic progression

advertisements

I came across this problem where you were given a number N as Input and then N numbers followed (where 3<=N<=2500). These N numbers were part of an Arithmetic Progression (of size N+1) from which one number was removed. So the task was to find that Missing number. For instance

5
1 3 5 9 11

The output is 7

I came up with two methods, the 2nd one passing all the test cases but the first one failing in certain (hidden) cases.

First I will explain the second method

METHOD II

Let diff=(last_number-first_number)/N
 //Considering 0 based indexing
 for i=0 to (N-2)
    if( array[i+1] is not equal to (array[i]+diff))
          print (array[i]+diff)
          break

This method passed all the test cases. Now the first method which I implemented and which failed certain test cases was as follows

METHOD I

 //Considering 0 based indexing
 for i=1 to (N-2)
      if (2*array[i] is not equal to (array[i-1]+array[i+1])) then
              if( (array[i]-array[i-1])< (array[i+1]-array[i]))
                      print 2*array[i]-array[i-1]
              else
                      print 2*array[i]-array[i+1]
              break

Can anyone explain what is wrong with METHOD I?? Which cases am I missing. Thanks.


Method 1 does not work when the numbers are in decreasing order.

For 7 5 1 output should be 3 but the algorithm will give 9.

Method 2 works in this case because the difference is correctly calculated as negative and the algorithm proceeds accordingly.