Can Make Arithmetic Progression From Sequence - Problem

A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

Example: The array [3, 5, 1] can be rearranged to [1, 3, 5] which forms an arithmetic progression with common difference 2.

Input & Output

Example 1 — Basic Case
$ Input: arr = [3,5,1]
Output: true
💡 Note: We can rearrange the array as [1,3,5] which forms an arithmetic progression with common difference 2.
Example 2 — Already Sorted
$ Input: arr = [1,2,4]
Output: false
💡 Note: The differences are 2-1=1 and 4-2=2. Since 1 ≠ 2, it cannot form an arithmetic progression.
Example 3 — Equal Elements
$ Input: arr = [1,1,1]
Output: true
💡 Note: All elements are the same, so the common difference is 0. This forms an arithmetic progression.

Constraints

  • 2 ≤ arr.length ≤ 1000
  • -106 ≤ arr[i] ≤ 106

Visualization

Tap to expand
Can Make Arithmetic Progression From Sequence INPUT Original Array: arr = [3, 5, 1] 3 idx 0 5 idx 1 1 idx 2 Can we rearrange this to form an Arithmetic Progression? AP Definition: Constant difference between consecutive terms n = 3, values: 3,5,1 ALGORITHM STEPS 1 Sort the Array [3,5,1] --> [1,3,5] 1 3 5 2 Calculate Difference d = arr[1] - arr[0] d = 3 - 1 = 2 3 Check All Pairs Verify each consecutive pair has same diff 3 - 1 = 2 [OK] 5 - 3 = 2 [OK] All differences equal! 4 Return Result All checks passed! --> Return true FINAL RESULT Rearranged Array (AP): 1 3 5 +2 +2 Common Difference: d = 2 Constant throughout! OUTPUT true [OK] Valid AP Found! Sequence: 1, 3, 5 Key Insight: For an Arithmetic Progression, after sorting, the difference between every consecutive pair must be equal. Time Complexity: O(n log n) for sorting. Space Complexity: O(1) if sorting in-place. Alternative: Use formula-based approach with min, max to achieve O(n) time using a HashSet. TutorialsPoint - Can Make Arithmetic Progression From Sequence | Optimal Solution (Sort + Check)
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~10 min Avg. Time
847 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