Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The input is small enough to examine every ordered index triple directly. Each good triple must satisfy all three pairwise distance limits; satisfying two does not automatically guarantee the third.
Approach
Use three nested loops with i < j < k. Check abs(arr[i] - arr[j]) <= a, abs(arr[j] - arr[k]) <= b, and abs(arr[i] - arr[k]) <= c, incrementing the answer only when all hold. Return the count. Increasing index bounds prevent duplicate counting while still distinguishing equal-valued elements at different positions. Equality with a threshold is allowed.
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
n = len(arr)
res = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
res += 1
return resComplexity analysis
For n = arr.length, the code checks every index triple, so time is O(n³) and auxiliary space is O(1).
