1228. Missing Number In Arithmetic Progression

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.

Then, a value from arr was removed that was not the first or last value in the array.

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 <= 1000
  • 0 <= arr[i] <= 10^5

Rust Solution

struct Solution;

impl Solution {
    fn missing_number(arr: Vec<i32>) -> i32 {
        let n = arr.len();
        let delta = (arr[n - 1] - arr[0]) / n as i32;
        for i in 1..n {
            let v = arr[0] + delta * i as i32;
            if arr[i] != v {
                return v;
            }
        }
        0
    }
}

#[test]
fn test() {
    let arr = vec![5, 7, 11, 13];
    let res = 9;
    assert_eq!(Solution::missing_number(arr), res);
    let arr = vec![15, 13, 12];
    let res = 14;
    assert_eq!(Solution::missing_number(arr), res);
}

Having problems with this solution? Click here to submit an issue on github.