LeetCode 1502: Can Make Arithmetic Progression From Sequence Solution
Master LeetCode problem 1502 (Can Make Arithmetic Progression From Sequence), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
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.
:
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1502 (Can Make Arithmetic Progression From Sequence)?
This page provides optimized solutions for LeetCode problem 1502 (Can Make Arithmetic Progression From Sequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1502 (Can Make Arithmetic Progression From Sequence)?
The time complexity for LeetCode 1502 (Can Make Arithmetic Progression From Sequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1502 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1502 in Java, C++, or Python.