Problem Description
Explanation:
To determine if an array can be rearranged to form an arithmetic progression, we need to check if the differences between any two consecutive elements are the same. We can achieve this by sorting the array and then checking if the differences between adjacent elements are consistent.
Algorithm:
- Sort the input array.
- Calculate the common difference between the first two elements.
- Iterate through the array and check if the differences between consecutive elements are the same as the common difference.
- If any difference is not equal to the common difference, return false. Otherwise, return true.
Time Complexity:
The time complexity of this solution is O(n log n) due to the sorting step where n is the number of elements in the input array.
Space Complexity:
The space complexity of this solution is O(1) as we are not using any extra space apart from a few variables.
:
Solutions
class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
Arrays.sort(arr);
int diff = arr[1] - arr[0];
for (int i = 2; i < arr.length; i++) {
if (arr[i] - arr[i - 1] != diff) {
return false;
}
}
return true;
}
}
Loading editor...