Problem
A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s
is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0]
for all valid i
.
For example, these are arithmetic sequences:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic :
1, 1, 2, 5, 7
You are given an array of n
integers, nums
, and two arrays of m
integers each, l
and r
, representing the m
range queries, where the ith
query is the range [l[i], r[i]]
. All the arrays are 0-indexed.
Return a list ofboolean
elements answer
, where answer[i]
is true
if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]]
can berearranged to form an arithmetic sequence, and false
otherwise.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == nums.length
m == l.length
m == r.length
2 <= n <= 500
1 <= m <= 500
0 <= l[i] < r[i] < n
-10^5 <= nums[i] <= 10^5
Solution
Method 1 – Sorting and Checking Differences
Intuition
The key idea is that a sequence can be rearranged into an arithmetic sequence if, after sorting, the difference between every two consecutive elements is the same. For each query, we extract the subarray, sort it, and check if all consecutive differences are equal.
Approach
- Initialize an empty list
ans
to store the results. - For each query, extract the subarray from
nums
using the indices froml[i]
tor[i]
. - Sort the subarray.
- Compute the difference between the first two elements.
- Iterate through the sorted subarray and check if every consecutive pair has the same difference.
- If all differences are equal, append
true
toans
; otherwise, appendfalse
. - Return
ans
after processing all queries.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * k log k)
, wherem
is the number of queries andk
is the maximum length of a subarray (since we sort each subarray). - 🧺 Space complexity:
O(k)
per query for the subarray copy.