Code Logo

Can Make Arithmetic Progression From Sequence

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[1,2]
Output
true
Explanation

Two elements always form an AP.

Example 2
Input
[-3,-1,-5,1]
Output
true
Explanation

Sorted: [-5,-3,-1,1], diff=2.

Example 3
Input
[1,2,4]
Output
false
Explanation

Sorted: [1,2,4], diff 1 then 2.

Example 4
Input
[1,7,13]
Output
true
Explanation

Sorted: [1,7,13], diff=6.

Example 5
Input
[3,5,1]
Output
true
Explanation

Sorted: [1,3,5], diff=2.

Algorithm Flow

Recommendation Algorithm Flow for Can Make Arithmetic Progression From Sequence
Recommendation Algorithm Flow for Can Make Arithmetic Progression From Sequence

Solution Approach

Sort array. Check that all consecutive differences equal the first difference.

function solution(arr) {
  arr.sort(function(a,b){return a-b;});
  var diff = arr[1] - arr[0];
  for (var i = 2; i < arr.length; i++) {
    if (arr[i] - arr[i-1] !== diff) return false;
  }
  return true;
}

Time O(n log n), Space O(1).

Best Answers

java
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;
    }
}