#1630
Medium Algorithms Arithmetic subarrays
Array Hash Table Sorting
83.8% acceptance
Feb 25, 2026
1896
210
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.
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]].
Return a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn check_arithmetic_subarrays(nums: Vec<i32>, l: Vec<i32>, r: Vec<i32>) -> Vec<bool> {
l.iter().zip(r.iter()).map(|(&li, &ri)| {
let mut sub: Vec<i32> = nums[li as usize..=ri as usize].to_vec();
sub.sort();
let diff = sub[1] - sub[0];
sub.windows(2).all(|w| w[1] - w[0] == diff)
}).collect()
}
}