text: Find the missing number in unordered Arithmetic Progression | Java program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Function Call
code: import java . util . Arrays ; class GFG { static int findMissing ( int arr [ ] , int left , int right , int diff ) { if ( right <= left ) return 0 ; int mid = left + ( right - left ) / 2 ; 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 ) ; } static int missingElement ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int diff = ( arr [ n - 1 ] - arr [ 0 ] ) / n ; return findMissing ( arr , 0 , n - 1 , diff ) ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 2 , 8 , 6 , 10 } ; int n = arr . length ; System . out . println ( missingElement ( arr , n ) ) ; } }