A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Given an array of numbers arr, return trueif the array can be rearranged to form an arithmetic progression. Otherwise, returnfalse.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Example 2:
Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-106 <= arr[i] <= 106
Solutions
Solution 1: Sorting + Traversal
Thinking
To decide whether the array can be rearranged into an arithmetic progression, trying every permutation is \(n!\), which is impossible even for \(n\) around a thousand. After a valid rearrangement every adjacent difference equals the same \(d\), so one canonical order suffices.
Sorting forces that order: the common difference must be the gap between consecutive sorted values. Checking that every adjacent pair matches the first gap is then a linear scan, and the sort is cheap enough for the given \(n\).
We can first sort the array \(\textit{arr}\), then traverse the array, and check whether the difference between adjacent items is equal.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Here, \(n\) is the length of the array \(\textit{arr}\).
Solution 1 spends \(O(n\log n)\) on sorting. If an arithmetic progression exists, its difference is fixed by the minimum \(a\) and maximum \(b\) as \(d=(b-a)/(n-1)\), which must be an integer. After placing the values in a hash set, it is enough to test that \(a, a+d, \ldots, a+(n-1)d\) all appear, which is linear time.
We first find the minimum value \(a\) and the maximum value \(b\) in the array \(\textit{arr}\). If the array \(\textit{arr}\) can be rearranged into an arithmetic sequence, then the common difference \(d = \frac{b - a}{n - 1}\) must be an integer.
We can use a hash table to record all elements in the array \(\textit{arr}\), then traverse \(i \in [0, n)\), and check whether \(a + d \times i\) is in the hash table. If not, it means that the array \(\textit{arr}\) cannot be rearranged into an arithmetic sequence, and we return false. Otherwise, after traversing the array, we return true.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array \(\textit{arr}\).