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
๐ŸŽน Piano Keys Arithmetic ProgressionStep 1: Scattered Keys on Table351Random positions - can't play melody yetStep 2: Arrange Keys on Piano (Sorted)135Sorted: 1, 3, 5Step 3: Measure Intervals Between Keys13522Equal intervals: โœ…Result: Can Play Arithmetic Progression Melody! ๐ŸŽต๐ŸŽน Play keys 1, 3, 5 with consistent 2-key intervals๐ŸŽฏ Key InsightWhy sorting works:โ€ข AP has unique order when arrangedโ€ข Sorting gives us that orderโ€ข Only need to check one arrangementTime Complexity:โ€ข Brute force: O(n! ร— n)โ€ข Optimal: O(n log n)10 elements: 36M vs 100 ops!
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!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen