#2367
Easy Algorithms Number of arithmetic triplets
Array Hash Table Two Pointers Enumeration
85.4% acceptance
Feb 25, 2026
1386
98
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, and
nums[k] - nums[j] == diff.
Return the number of unique arithmetic triplets.
Solution
Rust
Time O(n)
Space O(1)
use std::collections::HashSet;
impl Solution {
pub fn arithmetic_triplets(nums: Vec<i32>, diff: i32) -> i32 {
let set: HashSet<i32> = nums.iter().cloned().collect();
nums.iter()
.filter(|&&k| set.contains(&(k - diff)) && set.contains(&(k - 2 * diff)))
.count() as i32
}
}