Can Make Arithmetic Progression From Sequence

easy array sorting

Problem

Return true if the array can be reordered to form an arithmetic progression.

Inputarr = [3,5,1]
Outputtrue
Sorted: [1,3,5] — common difference 2.

def can_make_arithmetic_progression(arr):
    a = sorted(arr)
    d = a[1] - a[0]
    return all(a[i] - a[i-1] == d for i in range(2, len(a)))
function canMakeArithmeticProgression(arr) {
  const a = arr.slice().sort((x, y) => x - y);
  const d = a[1] - a[0];
  for (let i = 2; i < a.length; i++) if (a[i] - a[i-1] !== d) return false;
  return true;
}
class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        Arrays.sort(arr);
        int d = arr[1] - arr[0];
        for (int i = 2; i < arr.length; i++) if (arr[i] - arr[i-1] != d) return false;
        return true;
    }
}
bool canMakeArithmeticProgression(vector& arr) {
    sort(arr.begin(), arr.end());
    int d = arr[1] - arr[0];
    for (int i = 2; i < (int)arr.size(); i++) if (arr[i] - arr[i-1] != d) return false;
    return true;
}
Time: O(n log n) Space: O(1)