[LeetCode] Arithmetic Subarrays

1630. Arithmetic Subarrays

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
2
3
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9

The following sequence is not arithmetic:

1
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 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
bool qry(vector<int>& num, int l, int r) {
unordered_set<int> s;
int mi = INT_MAX, ma = INT_MIN;
for(int i = l; i <= r; i++) {
s.insert(num[i]);
mi = min(mi, num[i]);
ma = max(ma, num[i]);
}

if((ma - mi) % (r - l)) return false;

int diff = (ma - mi) / (r - l);
if(diff == 0) return s.size() == 1;
if(diff and s.size() != (r - l + 1)) return false;
int base = mi;
while(base <= ma) {
if(!s.count(base)) return false;
base += diff;
}
return true;
}
public:
vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {
int n = nums.size(), m = l.size();

vector<bool> res(m);
for(int i = 0; i < m; i++) {
res[i] = qry(nums,l[i],r[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/29/PS/LeetCode/arithmetic-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.