You are given a list of n
numbers that form an arithmetic progression except for one missing number. The numbers are sorted in strictly increasing order and exactly one number from the progression is missing from the list. Your task is to find and return the missing number.
arr
of length n
(where n >= 3
).
For example, given arr = [5, 7, 11, 13]
, the missing number is 9
because the arithmetic progression should be 5, 7, 9, 11, 13
.
At first glance, you might think to check every possible number between the first and last elements to see which is missing. However, since the numbers form an arithmetic progression, we can use the properties of such sequences to find the missing number more efficiently.
The key insight is that the "jump" between two adjacent numbers will be larger at the point where the missing number would have been.
Let's break down the optimized solution step-by-step:
diff = (arr[-1] - arr[0]) // len(arr)
.
diff
. If not, the missing number is between these two elements.
arr[i] + diff
where the anomaly is found.
This approach is efficient and leverages the properties of arithmetic progressions to avoid unnecessary computation.
Let's walk through an example with arr = [5, 7, 11, 13]
:
diff = (13 - 5) // 4 = 8 // 4 = 2
So, the missing number is 9
.
O(n)
to generate the full sequence and compare with input.O(n)
for the generated sequence.O(n)
— we scan the array once.O(1)
— we only use a few variables for calculation.The optimized solution is clearly better in both time and space, especially for large arrays.
By leveraging the properties of arithmetic progressions, we can efficiently find the missing number by:
This solution is elegant because it avoids unnecessary computation and uses mathematical reasoning to solve the problem in linear time and constant space.
class Solution:
def missingNumber(self, arr):
n = len(arr)
diff = (arr[-1] - arr[0]) // n
for i in range(n - 1):
if arr[i + 1] - arr[i] != diff:
return arr[i] + diff
# If not found in loop, missing number is at the end or start
return arr[0] + diff
class Solution {
public:
int missingNumber(vector<int>& arr) {
int n = arr.size();
int diff = (arr[n - 1] - arr[0]) / n;
for (int i = 0; i < n - 1; ++i) {
if (arr[i + 1] - arr[i] != diff) {
return arr[i] + diff;
}
}
// If not found in loop
return arr[0] + diff;
}
};
class Solution {
public int missingNumber(int[] arr) {
int n = arr.length;
int diff = (arr[n - 1] - arr[0]) / n;
for (int i = 0; i < n - 1; i++) {
if (arr[i + 1] - arr[i] != diff) {
return arr[i] + diff;
}
}
// If not found in loop
return arr[0] + diff;
}
}
var missingNumber = function(arr) {
const n = arr.length;
const diff = Math.floor((arr[n - 1] - arr[0]) / n);
for (let i = 0; i < n - 1; i++) {
if (arr[i + 1] - arr[i] !== diff) {
return arr[i] + diff;
}
}
// If not found in loop
return arr[0] + diff;
};