Leetcode 2367. Number of Arithmetic Triplets
You are given a 0-indexed, strictly increasing integer array nums
and a positive integer diff
. A triplet (i, j, k)
is an arithmetic triplet if the following conditions are met:
i < j < k
,nums[j] - nums[i] == diff
, andnums[k] - nums[j] == diff
.Return the number of unique arithmetic triplets.
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation: The triplets are (0, 2, 4) and (1, 3, 5).
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation: The triplets are (0, 2, 4) and (1, 3, 5).
nums
array?
nums
can be up to (10^4).nums
array?
nums
are integers within the range ([0, 200]).nums
?
nums
is strictly increasing, so no duplicates will be present.0
in that case.(i, j, k)
to be valid, the differences between the elements must satisfy:
nums[j] - nums[i] == diff
nums[k] - nums[j] == diff
nums[j] == nums[i] + diff
nums[k] == nums[j] + diff
nums
.nums[k]
:
nums[k] - diff
and nums[k] - 2 * diff
are present in the previously encountered elements.Here is the implementation based on the above strategy:
#include <vector>
#include <unordered_set>
class Solution {
public:
int arithmeticTriplets(std::vector<int>& nums, int diff) {
std::unordered_set<int> seen;
int count = 0;
for (int num : nums) {
if (seen.count(num - diff) && seen.count(num - 2 * diff)) {
count++;
}
seen.insert(num);
}
return count;
}
};
This code uses an unordered set to store the encountered numbers and checks for the presence of required numbers to form valid triplets in O(1) average time. The final count of such triplets is returned.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?