Leetcode 1502. Can Make Arithmetic Progression From Sequence
Given an array of numbers arr
, return true
if the array can be rearranged to form an arithmetic progression, otherwise, return false
.
An array is said to form an arithmetic progression if the difference between consecutive elements is the same.
Let’s implement the function following these steps:
public class Solution {
public boolean canMakeArithmeticProgression(int[] arr) {
if (arr.length < 2) {
return true;
}
Arrays.sort(arr);
int commonDifference = arr[1] - arr[0];
for (int i = 2; i < arr.length; i++) {
if (arr[i] - arr[i - 1] != commonDifference) {
return false;
}
}
return true;
}
}
O(n log n)
where n
is the length of the array.O(n)
for the validation loop.Thus, the overall time complexity of the solution is O(n log n) due to the sorting step.
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?