Leetcode 1502: Can Make Arithmetic Progression From Sequence

grid47
grid47
Exploring patterns and algorithms
Jun 9, 2024 6 min read

You are given an array of integers. Your task is to determine if the array can be rearranged to form an arithmetic progression. The array can be rearranged in any order, and the common difference between consecutive elements should be the same.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of integers, arr.
Example: [10, 20, 30]
Constraints:
• 2 <= arr.length <= 1000
• -10^6 <= arr[i] <= 10^6
Output: The output is a boolean indicating whether the array can be rearranged to form an arithmetic progression.
Example: true
Constraints:
• The array can have negative or positive numbers, and it may be sorted or unsorted initially.
Goal: The goal is to determine if the array can be rearranged into an arithmetic progression with a constant difference between consecutive elements.
Steps:
• Find the minimum and maximum values in the array.
• Check if the difference between the maximum and minimum values is divisible by the number of elements minus one.
• Calculate the common difference (d) using the formula (max - min) / (arr.size() - 1).
• Try to place each element in its correct position according to the common difference. If any element cannot be placed correctly, return false.
• If all elements are placed correctly, return true.
Goal: The array must have at least two elements, and the elements must be integers within the given range.
Steps:
• The array length is between 2 and 1000.
• Each element in the array is between -10^6 and 10^6.
Assumptions:
• The array contains at least two elements.
Input: [10, 20, 30]
Explanation: The elements can be rearranged to form an arithmetic progression with a common difference of 10.

Input: [1, 2, 4]
Explanation: The elements cannot be rearranged to form an arithmetic progression, as the difference between 2 and 4 is not consistent with any other pair of elements.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus