Given an array of integers arr
and three integers a
, b
, and c
, find the number of good triplets.
A triplet (arr[i], arr[j], arr[k])
is good if it satisfies the following conditions:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
a
, b
, and c
?
We need to iterate over all possible triplets (i, j, k)
in the array and check if they satisfy the given conditions. A brute force approach involves nested loops to examine all triplets.
The brute force method works in O(n^3)
time complexity because we are using three nested loops to iterate over the array elements. Given the constraints are typically low (for example, arr.length <= 100
), this complexity is acceptable for this problem.
Here’s the implementation of the described strategy:
def count_good_triplets(arr, a, b, c):
count = 0
n = len(arr)
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:
count += 1
return count
# Example usage
arr = [3,0,1,1,9,7]
a = 7
b = 2
c = 3
print(count_good_triplets(arr, a, b, c)) # Output: 4
This solution iterates through each triplet and checks the conditions directly, guaranteeing that all potential triplets are examined. While the time complexity is O(n^3)
, it is adequate for the typical constraints of such problems. If larger constraints exist, optimization techniques or different algorithms would be required.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?