Given an array of numbers arr
, determine if the array can be rearranged to form an arithmetic progression.
An array forms an arithmetic progression if the difference between consecutive elements is constant.
Example:
Input: arr = [3, 5, 1]
Output: true
Explanation: We can rearrange the array as [1, 3, 5] or [5, 3, 1] for both directions the difference is consistent.
Input: arr = [1, 2, 4]
Output: false
Explanation: No rearrangement can form a valid arithmetic progression.
Constraints:
2 <= arr.length <= 1000
-10^6 <= arr[i] <= 10^6
To determine if the elements can form an arithmetic progression:
def canMakeArithmeticProgression(arr):
arr.sort()
common_diff = arr[1] - arr[0]
for i in range(2, len(arr)):
if arr[i] - arr[i - 1] != common_diff:
return False
return True
# Example Usage:
# arr1 = [3, 5, 1]
# print(canMakeArithmeticProgression(arr1)) # Output: True
# arr2 = [1, 2, 4]
# print(canMakeArithmeticProgression(arr2)) # Output: False
Therefore, the overall time complexity is (O(n \log n)).
By sorting the array and then verifying the differences between consecutive elements, we can efficiently determine if the elements can form an arithmetic progression. The provided code follows this approach and ensures the task is completed within the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?