Can Make Arithmetic Progression From Sequence - Problem
An arithmetic progression (AP) is a sequence where the difference between consecutive elements remains constant. For example, [2, 4, 6, 8] has a common difference of 2, while [10, 7, 4, 1] has a common difference of -3.
Given an array of integers arr, determine if you can rearrange the elements to form an arithmetic progression. Return true if it's possible, false otherwise.
Key insight: You're allowed to reorder the array elements in any way you want - the challenge is determining if such an arrangement exists.
Input & Output
example_1.py โ Basic AP
$
Input:
arr = [3, 5, 1]
โบ
Output:
true
๐ก Note:
After sorting: [1, 3, 5]. Differences: 3-1=2, 5-3=2. All differences equal 2, so it forms an arithmetic progression.
example_2.py โ No valid AP
$
Input:
arr = [1, 2, 4]
โบ
Output:
false
๐ก Note:
After sorting: [1, 2, 4]. Differences: 2-1=1, 4-2=2. Since 1 โ 2, no arithmetic progression is possible.
example_3.py โ Two elements
$
Input:
arr = [7, 3]
โบ
Output:
true
๐ก Note:
Any array with 2 or fewer elements can always form an arithmetic progression. The difference would be 3-7=-4.
Constraints
- 2 โค arr.length โค 1000
- -106 โค arr[i] โค 106
Visualization
Tap to expand
Understanding the Visualization
1
Scattered Keys
Keys [3, 5, 1] are randomly placed on the table
2
Arrange in Order
Place them on piano: positions 1, 3, 5
3
Measure Intervals
Gap from 1โ3 is 2 keys, gap from 3โ5 is also 2 keys
4
Equal Intervals!
Since all gaps are equal, we can play a consistent melody
Key Takeaway
๐ฏ Key Insight: Sort first, then validate - if elements can form an AP, sorting reveals the unique valid arrangement to check!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code