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.
1var checkArithmeticSubarrays = function(nums, l, r) {
2 const result = [];
3 for (let i = 0; i < l.length; i++) {
4 const start = l[i];
5 const end = r[i];
6 const subarray = nums.slice(start, end + 1);
7 subarray.sort((a, b) => a - b);
8 result.push(isArithmetic(subarray));
9 }
10 return result;
11};
12
13function isArithmetic(arr) {
14 const diff = arr[1] - arr[0];
15 for (let i = 2; i < arr.length; i++) {
16 if (arr[i] - arr[i - 1] !== diff) return false;
17 }
18 return true;
19}
The JavaScript solution leverages the slice method to extract subarrays and sorts them using a comparison function for numeric sorting. It uses isArithmetic
to check if the sorted subarray forms an arithmetic sequence.
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.
This implementation determines if an arithmetic sequence can exist without sorting. It uses the maximum and minimum to calculate the step difference, creates an array to track positions within the expected arithmetic sequence, and checks if all positions are filled correctly. If any position is missing or repeated, it cannot be organized into an arithmetic sequence.