Count Good Triplets - Problem
Given an array of integers arr and three threshold values a, b, and c, your task is to count how many "good triplets" exist in the array.
A triplet (arr[i], arr[j], arr[k]) is considered good if it satisfies all of the following conditions:
0 ≤ i < j < k < arr.length(indices must be in ascending order)|arr[i] - arr[j]| ≤ a(first two elements are close enough)|arr[j] - arr[k]| ≤ b(second and third elements are close enough)|arr[i] - arr[k]| ≤ c(first and third elements are close enough)
Where |x| denotes the absolute value of x.
Goal: Return the total count of good triplets found in the array.
Example: If arr = [3,0,1,1,9,7] with a=7, b=2, c=3, then triplet (3,0,1) at indices (0,1,2) is good because |3-0|=3≤7, |0-1|=1≤2, and |3-1|=2≤3.
Input & Output
example_1.py — Python
$
Input:
arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
›
Output:
4
💡 Note:
The 4 good triplets are: (3,0,1) at indices (0,1,2), (3,0,1) at indices (0,1,3), (3,1,1) at indices (0,2,3), and (0,1,1) at indices (1,2,3). Each satisfies all three distance conditions.
example_2.py — Python
$
Input:
arr = [1,1,2,2,3], a = 0, b = 0, c = 1
›
Output:
0
💡 Note:
No triplets satisfy the strict conditions since a=0 and b=0 require adjacent elements to be identical, but no three consecutive elements form valid triplets with c=1.
example_3.py — Python
$
Input:
arr = [7,3,7,3,7], a = 4, b = 4, c = 0
›
Output:
4
💡 Note:
With c=0, only triplets where first and third elements are identical work. The triplets (7,3,7) appear at indices (0,1,2), (0,1,4), (0,3,2), and (2,3,4).
Visualization
Tap to expand
Understanding the Visualization
1
Generate All Triplets
Use three nested loops to create all possible combinations where i < j < k
2
Check Distance Conditions
For each triplet, verify that all three pairwise distances are within thresholds
3
Count Valid Groups
Increment counter when all conditions are satisfied
Key Takeaway
🎯 Key Insight: Since we need to count ALL good triplets and verify multiple distance conditions for each, the triple nested loop approach is both necessary and optimal for this problem.
Time & Space Complexity
Time Complexity
O(n³)
Three nested loops each running up to n times, resulting in cubic time complexity
⚠ Quadratic Growth
Space Complexity
O(1)
Only using a constant amount of extra space for the counter and loop variables
✓ Linear Space
Constraints
- 3 ≤ arr.length ≤ 100
- 0 ≤ arr[i] ≤ 1000
- 0 ≤ a, b, c ≤ 1000
- Small input size makes O(n³) solution acceptable
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code