Find the missing number in unordered Arithmetic Progression | Function to find the missing element ; Fix left and right boundary for binary search ; Find index of middle element ; Check if the element just after the middle element is missing ; Check if the element just before mid is missing ; Check if the elements till mid follow the AP , then recur for right half ; Else recur for left half ; Function to find the missing element in AP series ; Sort the array [ ] arr ; Calculate Common Difference ; Binary search for the missing ; Given array [ ] arr ; Function Call
function findMissing ( arr , left , right , diff ) { if ( right <= left ) return 0 ; let mid = left + parseInt ( ( right - left ) / 2 , 10 ) ; if ( arr [ mid + 1 ] - arr [ mid ] != diff ) return ( arr [ mid ] + diff ) ; if ( mid > 0 && arr [ mid ] - arr [ mid - 1 ] != diff ) return ( arr [ mid - 1 ] + diff ) ; if ( arr [ mid ] == arr [ 0 ] + mid * diff ) return findMissing ( arr , mid + 1 , right , diff ) ; return findMissing ( arr , left , mid - 1 , diff ) ; } function missingElement ( arr , n ) { arr . sort ( function ( a , b ) { return a - b } ) ; let diff = parseInt ( ( arr [ n - 1 ] - arr [ 0 ] ) / n , 10 ) ; return findMissing ( arr , 0 , n - 1 , diff ) ; } let arr = [ 2 , 8 , 6 , 10 ] ; let n = arr . length ; document . write ( missingElement ( arr , n ) ) ;