This is the title of the Leetcode 2367. The number of arithmetic triples
Gives you an array of integers nums with a subscript starting at 0 and strictly increasing and a positive integer diff. A triplet(i, j, k)is an arithmetic triplet if all of the following conditions are met:
i < j < k ,
nums[j] - nums[i] == diff
nums[k] - nums[j] == diff
this is my code
class Solution {
public:
int arithmeticTriplets(vector<int>& nums, int diff) {
int ans = 0;
for (int i = 0; i < nums.size() - 2; i++) {
for (int j = i + 1; i < nums.size() - 1; j++) {
if (nums[j] - nums[i] == diff) {
for (int k = j + 1; k < nums.size(); k++) {
if (nums[k] - nums[j] == diff) ans++;
}
}
}
}
return ans;
}
};
But I couldn’t pass the assessment
show that
==22==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x503000000090 at pc 0x558615c49233 bp 0x7fffb82e42b0 sp 0x7fffb82e42a8
>Solution :
In your second level loop, you never test the value of j, and since i is not updated, it can continue looping until nums[j] results in an out of bounds memory access.
for (int i = 0; i < nums.size() - 2; i++) { for (int j = i + 1; i < nums.size() - 1; j++) { if (nums[j] - nums[i] == diff) { for (int k = j + 1; k < nums.size(); k++) { if (nums[k] - nums[j] == diff) ans++; } } } }
You probably wanted:
for (int j = i + 1; j < nums.size() - 1; j++)