Sponsored
Sponsored
For each query, extract the subarray defined by the given l and r indices. Sort this subarray to determine if it can be rearranged into an arithmetic sequence. Once sorted, check if the difference between consecutive elements is constant throughout the subarray.
If the difference is consistent, then the subarray can be rearranged to form an arithmetic sequence, otherwise it cannot.
Time Complexity is O(m * n log n) because for each query, we may sort the subarray (n log n). The space complexity is O(n) for the auxiliary array created for each query.
1#include <vector>
2#include <algorithm>
3
4using namespace std;
5
6bool isArithmetic(vector<int>& arr) {
7 sort(arr.begin(), arr.end());
8 int diff = arr[1] - arr[0];
9 for (int i = 2; i < arr.size(); i++) {
10 if (arr[i] - arr[i - 1] != diff) return false;
11 }
12 return true;
13}
14
15vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
16 vector<bool> result;
17 for (int i = 0; i < l.size(); i++) {
18 vector<int> subarray(nums.begin() + l[i], nums.begin() + r[i] + 1);
19 result.push_back(isArithmetic(subarray));
20 }
21 return result;
22}
This C++ solution uses the STL sort functionality to order subarrays efficiently. The isArithmetic function checks if the sorted subarray has a consistent difference between consecutive elements.
Rather than sorting, we can try to compute the minimum and maximum of the subarray to figure out the common difference, because in an arithmetic series, the difference between consecutive terms should be consistent. For each candidate difference, check manually if the subarray can be transformed into a complete arithmetic sequence by verifying all expected elements.
Time Complexity: O(n) per query, where n is the length of the subarray due to linear scans. Space Complexity: O(n) for the boolean array used for tracking.
Java adopts a similar strategy, extracting minimum and maximum elements from each query subarray alongside using a HashSet to verify integrity across terms in the candidate arithmetic sequence.