Number of Arithmetic Triplets - Problem
You are given a strictly increasing integer array nums and a positive integer diff. Your task is to find all arithmetic triplets in the array.
An arithmetic triplet is a set of three elements at indices (i, j, k) where:
i < j < k(indices are in order)nums[j] - nums[i] == diff(first gap equals diff)nums[k] - nums[j] == diff(second gap equals diff)
Example: In array [0, 1, 4, 6, 7, 10] with diff = 3, the triplet (1, 4, 7) forms an arithmetic sequence because 4 - 1 = 3 and 7 - 4 = 3.
Return the total count of unique arithmetic triplets.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [0,1,4,6,7,10], diff = 3
โบ
Output:
2
๐ก Note:
There are 2 arithmetic triplets: (0,3,6) doesn't exist since 3 is not in array, but (1,4,7) and (4,7,10) are valid triplets where consecutive differences equal 3.
example_2.py โ No Triplets
$
Input:
nums = [4,5,6,7,8,9], diff = 2
โบ
Output:
2
๐ก Note:
The arithmetic triplets are (4,6,8) and (5,7,9). Each has differences of 2 between consecutive elements.
example_3.py โ Single Element
$
Input:
nums = [1,5,7,12,15,18], diff = 3
โบ
Output:
2
๐ก Note:
Two arithmetic triplets exist: (12,15,18) with differences of 3, but we need to check all possibilities systematically.
Visualization
Tap to expand
Understanding the Visualization
1
Build Lookup
Create hash set of all available notes (numbers)
2
Find Middle
For each note, check if it can be the middle of a harmony
3
Check Intervals
Verify that notes at exact intervals exist
4
Count Harmonies
Count all valid three-note arithmetic progressions
Key Takeaway
๐ฏ Key Insight: Use the middle element as anchor point - it's the most efficient way to verify arithmetic progressions in a sorted array!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(1) hash set operations for each element
โ Linear Growth
Space Complexity
O(n)
Hash set stores up to n elements from the input array
โก Linearithmic Space
Constraints
- 3 โค nums.length โค 1000
- 0 โค nums[i] โค 1000
- 1 โค diff โค 50
- nums is strictly increasing
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code