Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check we can rearrange array to make difference between each pair of elements same in Python
Suppose we have a list called nums, we have to check whether we can rearrange the order of nums in such a way that the difference between every pair of consecutive two numbers is same. This is essentially checking if the array can form an arithmetic progression.
So, if the input is like nums = [8, 2, 6, 4], then the output will be True, because if we rearrange nums like [2, 4, 6, 8], then the difference between every two pair of consecutive numbers is 2.
Algorithm
To solve this, we will follow these steps ?
N := size of nums
-
if N
return True
sort the list nums
targetDiff := nums[1] - nums[0]
-
for i in range 2 to N - 1, do
-
if nums[i] - nums[i - 1] is not same as targetDiff, then
return False
-
return True
Example
Let us see the following implementation to get better understanding ?
def solve(nums):
N = len(nums)
if N <= 2:
return True
nums.sort()
targetDiff = nums[1] - nums[0]
for i in range(2, N):
if nums[i] - nums[i - 1] != targetDiff:
return False
return True
# Test with example
nums = [8, 2, 6, 4]
print(f"Input: {nums}")
print(f"Can form arithmetic progression: {solve(nums)}")
# Additional test cases
print(f"\nTest case 1: {solve([1, 2, 3, 4])}") # True
print(f"Test case 2: {solve([1, 3, 7])}") # False
print(f"Test case 3: {solve([5])}") # True
Input: [8, 2, 6, 4] Can form arithmetic progression: True Test case 1: True Test case 2: False Test case 3: True
How It Works
The algorithm works by first sorting the array to arrange elements in ascending order. Once sorted, if the array can form an arithmetic progression, all consecutive differences should be equal. We calculate the target difference from the first two elements and verify that all subsequent pairs maintain this same difference.
Key Points
Arrays with 2 or fewer elements can always form an arithmetic progression
Sorting is essential to check the arithmetic progression property
Time complexity: O(n log n) due to sorting
Space complexity: O(1) excluding the input array
Conclusion
This approach efficiently determines if an array can be rearranged into an arithmetic progression by sorting and checking consecutive differences. The key insight is that sorting reveals the natural order needed for arithmetic progression.
