Missing Number In Arithmetic Progression Problem
Description
LeetCode Problem 1228.
In some array arr, the values were in arithmetic progression: the values arr[i + 1] - arr[i] are all equal for every 0 <= i < arr.length - 1.
A value from arr was removed that was not the first or last value in the array.
Given arr, return the removed value.
Example 1:
Input: arr = [5,7,11,13]
Output: 9
Explanation: The previous array was [5,7,9,11,13].
Example 2:
Input: arr = [15,13,12]
Output: 14
Explanation: The previous array was [15,14,13,12].
Constraints:
3 <= arr.length <= 10000 <= arr[i] <= 10^5- The given array is guaranteed to be a valid array.
Solution
Approach: Sum of the Arithmetic Progression
The removed value was not the first or the last, so the original progression started with arr[0], ended with arr[n-1], and had n + 1 terms. The sum of an arithmetic progression is (first + last) · (number of terms) / 2, so the original sum was
(arr[0] + arr[n-1]) * (n + 1) / 2
and the missing value is that minus the sum of arr. The product is always even (the sum of integers is an integer), so the division is exact.
This never needs the common difference, so the case where all values are equal (difference 0) needs no special handling: the formula then gives that same value back. With arr[i] <= 10^5 and at most 1001 terms, the original sum is about 108, so 32-bit integers are enough.
Complexity: O(n) time and O(1) extra space.
class Solution:
def missingNumber(self, arr: List[int]) -> int:
# The first and last values are still there, so the full progression had len(arr) + 1 terms.
full_sum = (arr[0] + arr[-1]) * (len(arr) + 1) // 2
return full_sum - sum(arr)