Count Good Triplets
Problem
Given an array arr and three integers a, b, c, count triplets (i, j, k) with i < j < k such that |arr[i]−arr[j]| ≤ a, |arr[j]−arr[k]| ≤ b, and |arr[i]−arr[k]| ≤ c.
arr = [3,0,1,1,9,7], a=7, b=2, c=34def count_good_triplets(arr, a, b, c):
n = len(arr)
count = 0
for i in range(n):
for j in range(i + 1, n):
if abs(arr[i] - arr[j]) > a:
continue
for k in range(j + 1, n):
if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
count += 1
return count
function countGoodTriplets(arr, a, b, c) {
const n = arr.length;
let count = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (Math.abs(arr[i] - arr[j]) > a) continue;
for (let k = j + 1; k < n; k++) {
if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) count++;
}
}
}
return count;
}
class Solution {
public int countGoodTriplets(int[] arr, int a, int b, int c) {
int n = arr.length, count = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
if (Math.abs(arr[i] - arr[j]) > a) continue;
for (int k = j + 1; k < n; k++)
if (Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) count++;
}
return count;
}
}
int countGoodTriplets(vector<int>& arr, int a, int b, int c) {
int n = arr.size(), count = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
if (abs(arr[i] - arr[j]) > a) continue;
for (int k = j + 1; k < n; k++)
if (abs(arr[j] - arr[k]) <= b && abs(arr[i] - arr[k]) <= c) count++;
}
return count;
}
Explanation
A "good" triplet must satisfy three independent distance conditions at once, and the constraints are tiny (n is small). So the cleanest approach is to enumerate every ordered triple i < j < k and test it directly.
We loop i, then j > i, then k > j. The triple nesting guarantees we generate each combination exactly once, never repeating or reordering indices.
A small optimization: the first condition |arr[i]−arr[j]| ≤ a involves only i and j. If it already fails we continue and skip the entire inner k loop, pruning a lot of work.
For each surviving k we check the remaining two conditions and increment the counter when all three hold. With n elements this is O(n³) time but O(1) extra space, which is fine for the small input size.
Example: arr = [3,0,1,1,9,7], a=7, b=2, c=3. Triples like (0,1,2) with values 3,0,1 pass all three checks; in total exactly 4 triples qualify.