Number of Arithmetic Triplets - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,1,4,6,7,10], diff = 3
Output: 2
💡 Note: Two arithmetic triplets: (1,4,7) with differences 4-1=3 and 7-4=3, and (4,7,10) with differences 7-4=3 and 10-7=3
Example 2 — Single Triplet
$ Input: nums = [4,5,6,7,8,9], diff = 2
Output: 2
💡 Note: Two arithmetic triplets: (4,6,8) and (5,7,9), both with difference 2
Example 3 — No Triplets
$ Input: nums = [1,2,3], diff = 5
Output: 0
💡 Note: No arithmetic triplets possible with difference 5 in this small array

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 200
  • The given array is strictly increasing
  • 1 ≤ diff ≤ 50

Visualization

Tap to expand
Number of Arithmetic Triplets (diff=3)0146710+3+3+3+3Triplet 1: (1,4,7) → 4-1=3, 7-4=3Triplet 2: (4,7,10) → 7-4=3, 10-7=3Result: 2 arithmetic triplets
Understanding the Visualization
1
Input
Array [0,1,4,6,7,10] with diff=3
2
Process
Find triplets where consecutive differences equal 3
3
Output
Count of valid arithmetic triplets: 2
Key Takeaway
🎯 Key Insight: For each element as middle, check if both arithmetic partners exist using hash set lookup
Asked in
Meta 15 Google 12
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen