Look for missing items in arithmetic progression.
E.g.input:arr[] = {2, 4, 8, 10, 12, 14}
Output:6
input:arr[] = {1, 6, one, +, +};
Output:26.
Binary search is used. If Arr[mid]-arr[left] = = (mid-left) * diff, the missing part is on the right side of mid.
Otherwise the missing part is included on the left side of the mid.
Time Complexity:o (LOGN). Space:o (1).
1 Public classMain {2 3 Public Static voidMain (string[] args) {4 Try{5 int[] arr1 = {2, 4, 8, 10, 12, 14};6 int[] arr2 = {1, 6, 11, 16, 21, 31};7 int[] Arr3 = {1, 6};8 System.out.println (findmissing (arr1));9 System.out.println (findmissing (ARR2));Ten One System.out.println (findmissing (ARR3)); A -}Catch(IllegalArgumentException e) { - System.out.println (E.getmessage ()); the } - } - - Private Static intFindmissing (int[] arr)throwsillegalargumentexception{ + if(arr = =NULL|| Arr.length < 3){ - Throw NewIllegalArgumentException ("Invalid input!"); + } A intLen =arr.length; at intL = 0; - intr = len-1; - intdiff = (Arr[r]-arr[l])/Len; - System.out.println (diff); - while(L <=R) { - intMID = L + (r-l)/2; in if(Arr[mid]-arr[l] = = (mid-l) *diff) { -L = mid+1; to}Else{ +R =mid; - } the } * returnARR[R]-diff; $ }Panax Notoginseng}
Find Missing term in arithmetic progression arithmetic progression missing item