Can Make Arithmetic Progression From Sequence
Problem
Return true if the array can be reordered to form an arithmetic progression.
arr = [3,5,1]truedef 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;
}
Explanation
An arithmetic progression is a sequence where each step changes by the same amount. The easiest way to test for one is to sort the numbers first, since any valid progression, once sorted, simply increases by a fixed gap.
After sorting a, we compute the expected common difference from the first two elements: d = a[1] - a[0]. Then we walk the rest of the array and confirm every neighboring pair has that same gap.
If any pair fails the check a[i] - a[i-1] == d, the sequence cannot form a progression and we return false. If all pairs match, it can, so we return true.
Example: arr = [3, 5, 1]. Sorted it is [1, 3, 5], so d = 2. The gap from 3 to 5 is also 2, so every step matches and the answer is true.