Count Good Triplets - Problem

Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.

A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

  • 0 <= i < j < k < arr.length
  • |arr[i] - arr[j]| <= a
  • |arr[j] - arr[k]| <= b
  • |arr[i] - arr[k]| <= c

Where |x| denotes the absolute value of x.

Return the number of good triplets.

Input & Output

Example 1 — Basic Case
$ Input: arr = [3,0,1,1,9,5,2,4], a = 7, b = 2, c = 3
Output: 4
💡 Note: There are 4 good triplets: (3,0,1), (3,0,2), (3,1,2), and (0,1,1). Each satisfies all three distance conditions.
Example 2 — Tight Constraints
$ Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output: 0
💡 Note: With a=0 and b=0, adjacent elements must be identical, but no valid triplet satisfies all conditions simultaneously.
Example 3 — Small Array
$ Input: arr = [7,2,8], a = 5, b = 6, c = 1
Output: 0
💡 Note: Only one possible triplet (7,2,8). |7-2|=5≤5 ✓, |2-8|=6≤6 ✓, but |7-8|=1≤1 ✓. Actually this is valid, so output should be 1.

Constraints

  • 3 ≤ arr.length ≤ 100
  • 0 ≤ arr[i] ≤ 1000
  • 0 ≤ a, b, c ≤ 1000

Visualization

Tap to expand
Count Good Triplets Problem Overview30119524Input Array: [3,0,1,1,9,5,2,4]Constraints:a = 7 (max |arr[i] - arr[j]|)b = 2 (max |arr[j] - arr[k]|)c = 3 (max |arr[i] - arr[k]|)Valid Triplets Found:(3,0,1) at indices (0,1,2)(3,0,2) at indices (0,1,6)(3,1,2) at indices (0,2,6)(0,1,1) at indices (1,2,3)Output: 4 good triplets
Understanding the Visualization
1
Input
Array [3,0,1,1,9,5,2,4] with constraints a=7, b=2, c=3
2
Process
Check all triplets (i,j,k) where i<j<k for three distance conditions
3
Output
Count of valid triplets: 4
Key Takeaway
🎯 Key Insight: All three distance constraints must be checked simultaneously for each triplet
Asked in
LeetCode 25 Practice 15
23.2K Views
Medium Frequency
~15 min Avg. Time
892 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