Given a sequence of n numbers such that the difference between the consecutive terms is constant, find the missing term in logarithmic time. Assume that the first and last elements are always part of the input sequence and the missing number lies between index 1 to n-1.

For example,

Input:  [5, 7, 9, 11, 15]
Output: The missing term is 13
 
Input:  [1, 4, 7, 13, 16]
Output: The missing term is 10

Practice this problem

A simple solution would be to run a linear search on the array and find the missing element by comparing the difference of adjacent array elements with the sequence’s common difference. We can find the common difference between successive elements of the sequence by using the formula:

common difference = (last element in sequence – first element in sequence) / n

Here, n is the total number of elements in the sequence. The problem with this approach is that its worst-case time complexity is O(n). This solution also does not take advantage of the fact that the input is sorted in ascending or descending order.

 
Whenever we are asked to perform a search on a sorted array, we should always think of a binary search algorithm. We can easily solve this problem in O(log(n)) time by modifying the binary search algorithm. The idea is to check the difference of middle element with its left and right neighbor. If the difference is not equal to the common difference, then we know that the missing number lies between the middle element and its left or right neighbor. If the difference is the same as common difference of the sequence, reduce our search space and the left subarray nums[low…mid-1] or right subarray nums[mid+1…high] depending upon if the missing element lies on the left subarray or not.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

The missing term is 13

Java


Download  Run Code

Output:

The missing term is 13

Python


Download  Run Code

Output:

The missing term is 13