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 INPUT nums array (strictly increasing) 0 i=0 1 i=1 4 i=2 6 i=3 7 i=4 10 i=5 diff = 3 Arithmetic Triplet (i,j,k): nums[j] - nums[i] = diff nums[k] - nums[j] = diff where i < j < k ALGORITHM STEPS 1 Build Hash Set Store all nums in a set {0, 1, 4, 6, 7, 10} 2 For each num in array Check if triplet exists 3 Lookup in O(1) Check num+diff, num+2*diff num=0: 0+3=3? NO, 0+6=6? -- num=1: 1+3=4? OK, 1+6=7? OK num=4: 4+3=7? OK, 4+6=10? OK num=6,7,10: incomplete 4 Count valid triplets Increment count when found Time: O(n) | Space: O(n) FINAL RESULT Found Arithmetic Triplets: Triplet 1: (1, 2, 4) nums: [1, 4, 7] 4-1=3, 7-4=3 [OK] Triplet 2: (2, 3, 5) nums: [4, 7, 10] 7-4=3, 10-7=3 [OK] Output 2 2 unique arithmetic triplets with difference = 3 Key Insight: Using a Hash Set allows O(1) lookup for checking if num+diff and num+2*diff exist in the array. For each element, we only need to verify two values exist, turning a potential O(n^3) brute force solution into an efficient O(n) algorithm. The triplet conditions are checked in constant time. TutorialsPoint - Number of Arithmetic Triplets | Hash Set Lookup Approach
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