Program to check subarrays can be rearranged from arithmetic sequence or not in Python

Given a sequence of numbers and range queries, we need to check if subarrays can be rearranged to form arithmetic sequences. An arithmetic sequence has a constant difference between consecutive elements.

A sequence is arithmetic if it has at least two elements and the difference between consecutive elements remains the same. Examples include [2, 4, 6, 8, 10], [5, 5, 5, 5], and [4, -2, -8, -14].

Problem Example

For nums = [6,8,7,11,5,9], l = [0,0,2], r = [2,3,5] ?

  • Query [0, 2]: subarray [6,8,7] can be rearranged as [6,7,8] (difference = 1)

  • Query [0, 3]: subarray [6,8,7,11] cannot form arithmetic sequence

  • Query [2, 5]: subarray [7,11,5,9] can be rearranged as [5,7,9,11] (difference = 2)

Algorithm Steps

To solve this problem ?

  • Initialize result list with all True values

  • For each query range, extract the subarray

  • Sort the subarray to arrange elements in order

  • Calculate differences between consecutive elements

  • If all differences are equal, it forms an arithmetic sequence

Implementation

def solve(nums, l, r):
    result = [True] * len(l)
    
    for i in range(len(l)):
        # Extract subarray for current query
        data = nums[l[i]:r[i]+1]
        data.sort()
        
        # Calculate differences between consecutive elements
        differences = []
        for j in range(len(data) - 1):
            differences.append(data[j+1] - data[j])
        
        # Check if all differences are the same
        unique_differences = list(set(differences))
        if len(unique_differences) != 1:
            result[i] = False
    
    return result

# Test the function
nums = [6, 8, 7, 11, 5, 9]
l = [0, 0, 2]
r = [2, 3, 5]
print(solve(nums, l, r))
[True, False, True]

How It Works

For each query, we extract the subarray and sort it. Then we calculate differences between consecutive elements. If all differences are identical, the subarray can form an arithmetic sequence.

For the first query [0, 2], subarray [6, 8, 7] becomes [6, 7, 8] after sorting, with differences [1, 1] − all equal, so it's arithmetic.

Conclusion

This solution efficiently checks if subarrays can be rearranged into arithmetic sequences by sorting and verifying uniform differences. The time complexity is O(k × n log n) where k is the number of queries and n is the average subarray length.

Updated on: 2026-03-26T13:56:33+05:30

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements