Skip to content

2367. Number of Arithmetic Triplets 👍

  • Time: $O(n)$
  • Space: $O(200) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int arithmeticTriplets(vector<int>& nums, int diff) {
    constexpr int kMax = 200;
    int ans = 0;
    vector<bool> count(kMax + 1);

    for (const int num : nums) {
      if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff])
        ++ans;
      count[num] = true;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int arithmeticTriplets(int[] nums, int diff) {
    final int kMax = 200;
    int ans = 0;
    boolean[] count = new boolean[kMax + 1];

    for (final int num : nums) {
      if (num >= 2 * diff && count[num - diff] && count[num - 2 * diff])
        ++ans;
      count[num] = true;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def arithmeticTriplets(self, nums: list[int], diff: int) -> int:
    kMax = 200
    ans = 0
    count = [False] * (kMax + 1)

    for num in nums:
      if num >= 2 * diff and count[num - diff] and count[num - 2 * diff]:
        ans += 1
      count[num] = True

    return ans