[LeetCode]#2367. Number of Arithmetic Triplets

Fatboy Slim
1 min readNov 22, 2022

--

Environment: Python 3.8

Key technique: in

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.

Example 1:

Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.
(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3.

Analysis:

  1. Check nums[i]+diff and nums[i]+2*diff in nums

Solution:

class Solution:
def arithmeticTriplets(self, nums, diff):
ans=0
for i in range(len(nums)):
if nums[i]+diff in nums and nums[i]+diff*2 in nums:
ans+=1
return ans

Submissions:

Reference:

https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2395275/Python-oror-Easy-Approach

--

--