Can Make Arithmetic Progression From Sequence
Given an array of numbers, determine if it can be rearranged to form an arithmetic progression (AP). An AP is a sequence where the difference between consecutive terms is constant.
Sort the array. In an AP, the differences between consecutive elements must all be equal. After sorting, compute the difference between the first two elements. Then check if every subsequent pair has the same difference.
Time is O(n log n) for sorting. Space is O(1).
Edge cases include fewer than 3 elements (always true), an array with equal elements (difference 0), and negative numbers.
To check if a sequence can be an arithmetic progression, sorting is required because elements can be rearranged arbitrarily. After sorting, a constant difference confirms an AP exists. The edge case of fewer than two elements always returns true.
The constant difference check after sorting is O(n). This property of APs means that sorted order reveals the common difference instantly. The edge case of single or double elements trivially forms an arithmetic progression since there are no constraints on differences. The single-pass verification after sorting makes this an O(n log n) algorithm. For very large arrays, the sorting step dominates the time complexity, while the verification step is linear.Example Input & Output
Two elements always form an AP.
Sorted: [-5,-3,-1,1], diff=2.
Sorted: [1,2,4], diff 1 then 2.
Sorted: [1,7,13], diff=6.
Sorted: [1,3,5], diff=2.
Algorithm Flow

Solution Approach
Sort array. Check that all consecutive differences equal the first difference.
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public boolean solution(int[] arr) {
if (arr.length<2) return true;
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
