You are given a 0-indexed integer array nums
and an 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
nums[k] - nums[j] == diff
Return the number of unique arithmetic triplets.
Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
Explanation:
(0, 1, 2), [0, 1, 4] and (1, 2, 3), [1, 4, 7] are the arithmetic triplets.
Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
Explanation:
(0, 2, 4), [4, 6, 8] and (1, 3, 5), [5, 7, 9] are the arithmetic triplets.
Let’s start with the simplest brute-force approach:
def arithmeticTriplets(nums, diff):
triplet_count = 0
n = len(nums)
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
if nums[j] - nums[i] == diff and nums[k] - nums[j] == diff:
triplet_count += 1
return triplet_count
def arithmeticTriplets(nums, diff):
num_set = set(nums)
triplet_count = 0
for num in nums:
if (num - diff in num_set) and (num - 2 * diff in num_set):
triplet_count += 1
return triplet_count
Thus, the optimized approach is preferable for larger input sizes.
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?