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: 1
💡 Note: Only one possible triplet (7,2,8). |7-2|=5≤5 ✓, |2-8|=6≤6 ✓, |7-8|=1≤1 ✓. This triplet satisfies all conditions.

Constraints

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

Visualization

Tap to expand
Count Good Triplets INPUT arr = [3,0,1,1,9,5,2,4] 3 i=0 0 i=1 1 i=2 1 i=3 9 i=4 5 i=5 2 i=6 4 i=7 Parameters: a = 7 b = 2 c = 3 Conditions for Good Triplet: 0 <= i < j < k < n |arr[i] - arr[j]| <= a |arr[j] - arr[k]| <= b |arr[i] - arr[k]| <= c Find all (i, j, k) triplets satisfying conditions ALGORITHM STEPS 1 Triple Nested Loop For each i, j, k where i < j < k 2 Check Condition 1 |arr[i] - arr[j]| <= a 3 Check Condition 2 |arr[j] - arr[k]| <= b 4 Check Condition 3 |arr[i] - arr[k]| <= c Valid Triplets Found: (0,1,2): |3-0|=3<=7 OK (0,1,3): |3-0|=3<=7 OK (2,3,6): |1-1|=0<=7 OK (3,5,6): |1-5|=4<=7 OK All 3 conditions pass! FINAL RESULT Good Triplets Count: 4 4 Good Triplets: Triplet 1: (3, 0, 1) indices (0, 1, 2) Triplet 2: (3, 0, 1) indices (0, 1, 3) Triplet 3: (1, 1, 2) indices (2, 3, 6) Triplet 4: (1, 5, 2) indices (3, 5, 6) Output: 4 Key Insight: Brute force O(n^3) checks all triplets where i < j < k. For small arrays (n <= 100), this is efficient. Early termination: If condition 1 fails, skip inner loops. Each triplet must satisfy ALL three distance constraints. TutorialsPoint - Count Good Triplets | Optimal Solution Time: O(n^3) | Space: O(1)
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