Formatted question description: https://leetcode.ca/all/1502.html

1502. Can Make Arithmetic Progression From Sequence (Easy)

Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.

 

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
  • -10^6 <= arr[i] <= 10^6

Related Topics:
Array, Sort

Solution 1.

// OJ: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/

// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& A) {
        sort(begin(A), end(A));
        int d = A[1] - A[0];
        for (int i = 2; i < A.size(); ++i) {
            if (A[i] - A[i - 1] != d) return false;
        }
        return true;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/

// Time: O(N)
// Space: O(1)
// Ref: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720152/O(n)-time-O(1)-space
class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& A) {
        int mn = *min_element(begin(A), end(A)), mx = *max_element(begin(A), end(A)), N = A.size();
        if ((mx - mn) % (N - 1)) return false;
        int d = (mx - mn) / (N - 1);
        for (int i = 0; i < N;) {
            if (A[i] == mn + i * d) ++i;
            else if ((A[i] - mn) % d) return false;
            else {
                int j = (A[i] - mn) / d;
                if (j < i || A[i] == A[j]) return false;
                swap(A[i], A[j]);
            }
        }
        return true;
    }
};

Java

class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        if (arr.length == 2)
            return true;
        Arrays.sort(arr);
        int length = arr.length;
        int difference = arr[1] - arr[0];
        for (int i = 2; i < length; i++) {
            if (arr[i] - arr[i - 1] != difference)
                return false;
        }
        return true;
    }
}

All Problems

All Solutions