Missing Number in An Arithmetic Progression in JavaIt is very interesting problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to find missing number in an arithmetic progression in Java with different approaches and logic. Also, we will create Java programs for the same. Problem StatementAn array is given. The array contains some numbers that represent an arithmetic progression. In the arithmetic progression, one number is missing. The task is to find that missing number. Example 1: Input: int arr[] = {3, 5, 7, 9, 11, 15, 17, 19} Output: 13 Explanation: If we put the number 13 after number 11 in the input array, the arithmetic progression is complete. Hence, the answer is 13 Example 2: Input: int arr[] = {1, 7, 13, 19, 31, 37, 43} Output: 25 Explanation: If we put the number 25 after the number 19 in the input array, the arithmetic progression is complete. Hence, the answer is 25. Example 3: Input: int arr[] = {25, 18, 4, -3, -10, -17, -24} Output: 11 Explanation: If we put the number 11 after the number 18 in the input array, the arithmetic progression is complete. Hence, the answer is 11. Solution to the ProblemUsing Arithmetic Progression FormulaThe sum of the numbers in an arithmetic progression whose first term is a1 and the last term is an, and the total term is n is: Sn = (n x (a1 + an) ) / 2. Thus, we can compute the sum of the input array. It is because we know the first, last, and size of the input array. If we take the reference of example 1, we get: S9 = (9 x (3 + 19)) / 2 = (9 x 22) / 2 = 198 / 2 = 99 (9 is the size of the input array including the missing element) Now, iterate over the array and find the sum of the elements present. We get Sum of elements: 3 + 5 + 7 + 9 + 11 + 15 + 17 + 19 = 86 Now, subtract S8 with the sum of elements of the input array. We get 99 - 86 = 13, which is the missing element of the arithmetic progression. The following program implements the same concept. FileName: MissingElementAP.java Output: For the input array: 3 5 7 9 11 15 17 19 The missing element is: 13 For the input array: 1 7 13 19 31 37 43 The missing element is: 25 For the input array: 25 18 4 -3 -10 -17 -24 The missing element is: 11 Complexity Analysis: Since the program is using the binary search, the time complexity of the program is O(n), where n is the total number of elements present in the input array. The program is not using any auxiliary space. Therefore, the space complexity of the program is constant, i.e., O(1). |