Can Make Arithmetic Progression From Sequence — LeetCode 1502 Python Solution
- Problem
- #1502
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- arr = [3,5,1]
- Output
- true
- Explanation
- We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Python solution
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
arr.sort()
d = arr[1] - arr[0]
return all(b - a == d for a, b in pairwise(arr))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1502. Can Make Arithmetic Progression From Sequence is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1502. Can Make Arithmetic Progression From Sequence?
- LeetCode 1502. Can Make Arithmetic Progression From Sequence is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1502. Can Make Arithmetic Progression From Sequence?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 1502. Can Make Arithmetic Progression From Sequence?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 1502. Can Make Arithmetic Progression From Sequence cover?
- LeetCode 1502. Can Make Arithmetic Progression From Sequence is tagged Array and Sorting on LeetCode.