Leetcode 1534. Count Good Triplets
Given an array of integers arr
, and three integers a
, b
and c
. You need to return the number of good triplets.
A triplet (arr[i], arr[j], arr[k])
is a good triplet if the following conditions are true:
0 <= i < j < k < len(arr)
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
a
, b
, and c
?
arr
will have 3 to 100 elements. Each element in arr
will be between 0
and 1000
. a
, b
, and c
will be between 0
and 1000
.a
, b
, and c
, and varying values within arr
.To solve this problem, we need to iterate through all possible triplets (i, j, k)
where i < j < k
and check if they satisfy the given conditions. Given the constraints (length of array up to 100), a triple nested loop solution will be feasible and simple to implement.
i
, j
, and k
.(arr[i], arr[j], arr[k])
, check the conditions:
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Here’s the C++ implementation of the above strategy:
#include <vector>
#include <cmath> // for abs
class Solution {
public:
int countGoodTriplets(std::vector<int>& arr, int a, int b, int c) {
int count = 0;
int n = arr.size();
for (int i = 0; i < n - 2; ++i) {
for (int j = i + 1; j < n - 1; ++j) {
for (int k = j + 1; k < n; ++k) {
if (std::abs(arr[i] - arr[j]) <= a &&
std::abs(arr[j] - arr[k]) <= b &&
std::abs(arr[i] - arr[k]) <= c) {
++count;
}
}
}
}
return count;
}
};
O(n^3)
time, where n
is the number of elements in the array. This is because we are using three nested loops to iterate over all possible triplets.O(1)
as we are only using a few extra variables (the count and loop indices).Given the constraints (with n
up to 100), this time complexity is acceptable and should run efficiently within those limits.
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?