Missing Number In Arithmetic Progression

easy math arithmetic progression sum formula

Problem

In an array of integers arr, the values form an arithmetic progression (consecutive elements share a constant difference). Exactly one value has been removed from somewhere in the middle — never the first or last element. Return that missing value.

Inputarr = [5, 7, 11, 13]
Output9
The full progression is 5, 7, 9, 11, 13 with common difference 2; the missing value is 9.

def missing_number(arr):
    n = len(arr)
    expected = (arr[0] + arr[-1]) * (n + 1) // 2
    actual = sum(arr)
    return expected - actual
function missingNumber(arr) {
  const n = arr.length;
  const expected = (arr[0] + arr[n - 1]) * (n + 1) / 2;
  let actual = 0;
  for (const x of arr) actual += x;
  return expected - actual;
}
class Solution {
    public int missingNumber(int[] arr) {
        int n = arr.length;
        int expected = (arr[0] + arr[n - 1]) * (n + 1) / 2;
        int actual = 0;
        for (int x : arr) actual += x;
        return expected - actual;
    }
}
int missingNumber(vector<int>& arr) {
    int n = arr.size();
    int expected = (arr[0] + arr[n - 1]) * (n + 1) / 2;
    int actual = 0;
    for (int x : arr) actual += x;
    return expected - actual;
}
Time: O(n) Space: O(1)