#1502

Can Make Arithmetic Progression From Sequence

Easy
ArraySortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting the array first, then checking the differences between consecutive elements. This is efficient because it reduces the problem to a simple linear scan after sorting.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the array.
  2. 2Step 2: Calculate the common difference using the first two elements.
  3. 3Step 3: Iterate through the sorted array and check if the difference between consecutive elements matches the common difference.
  4. 4Step 4: If all differences match, return true; otherwise, return false.
solution.py7 lines
1def canMakeArithmeticProgression(arr):
2    arr.sort()
3    diff = arr[1] - arr[0]
4    for i in range(2, len(arr)):
5        if arr[i] - arr[i - 1] != diff:
6            return False
7    return True

Complexity note: The time complexity is O(n log n) due to sorting the array. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Sorting the array is crucial as any valid arithmetic progression will be in sorted order.
  • 2The common difference between consecutive elements must be consistent throughout the array.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.