Arithmetic Subarrays LeetCode solution in C++

1
class Solution {
2
public:
3
vector<bool> checkArithmeticSubarrays(vector<int> &nums, vector<int> &l, vector<int> &r) {
4
vector<bool> ans(l.size(), false);
5
for (int i = 0; i < l.size(); i++) {
6
// if the sub array size is equal to 2
7
if (r[i] - l[i] + 1 == 2)
8
ans[i] = true;
9
else if (isArthemetic(nums, l[i], r[i]))
10
ans[i] = true;
11
}
12
return ans;
13
}
14

15
// return true if the sub array can be rearranged in a arthemetic sequence
16
bool isArthemetic(vector<int> &nums, int start, int end) {
17
// get the maximum and min elements
18
int mini = INT_MAX;
19
int maxi = INT_MIN;
20
for (int i = start; i <= end; i++) {
21
mini = min(nums[i], mini);
22
maxi = max(nums[i], maxi);
23
}
24

25
// when mini==maxi it means all the elements are same in the sub array
26
if (mini == maxi) return true;
27

28
// we cant have same common difference betweeen two adjacent elements
29
// when we arrange in arthemetic sequence
30
if ((maxi - mini) % (end - start) != 0) return false;
31

32
// the diff between every two integers when we rearrange sub array
33
int diff = (maxi - mini) / (end - start);
34

35
// to check if the duplicate elemnts are present
36
// ex- [2,4,6,6]
37
// 6 is repeating two times
38
vector<bool> present(end - start + 1, false);
39
for (int i = start; i <= end; i++) {
40
// we cant set a index of nums[i]
41
if ((nums[i] - mini) % diff != 0) return false;
42

43
int ind = (nums[i] - mini) / diff;
44

45
// same element is alreeady repeated ( 6 in the above example)
46
if (present[ind]) return false;
47
// mark it presence
48
present[ind] = true;
49
}
50
return true;
51
}
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0