Problem Description
Given an array of integers and several range queries defined by two arrays l and r, determine whether the subarray for each query can be rearranged to form an arithmetic sequence. An arithmetic sequence is one in which the difference between consecutive elements is constant.
Key Insights
- To validate an arithmetic sequence, sorting the subarray helps to easily compare consecutive differences.
- A subarray with only two elements is inherently arithmetic.
- For each query, extracting and sorting the subarray followed by checking consecutive differences gives a clear solution.
- The constraints (n, m up to 500) allow the use of sorting for each query without performance issues.
Space and Time Complexity
Time Complexity: O(m * k log k), where m is the number of queries and k is the average length of the subarray. In the worst case, k can be O(n), so it becomes O(m * n log n).
Space Complexity: O(k) per query for the temporary subarray storage.
Solution
For each query, extract the subarray defined by indices [l[i], r[i]]. If the subarray length is 2, it is automatically arithmetic. Otherwise, sort the subarray and calculate the common difference between the first two elements. Then, iterate through the sorted subarray to check if every consecutive difference matches the common difference. If a mismatch is found, the subarray cannot be rearranged to form an arithmetic sequence. This approach leverages sorting to simplify the verification of consecutive differences.