Leetcode 1534. Count Good Triplets
Given an array of integers arr
, and three integers a
, b
and c
. You need to count 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
Return the number of good triplets.
3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
0
.Here’s a straightforward implementation in Java using the brute force method:
public class CountGoodTriplets {
public int countGoodTriplets(int[] arr, int a, int b, int c) {
int count = 0;
int n = arr.length;
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 (Math.abs(arr[i] - arr[j]) <= a
&& Math.abs(arr[j] - arr[k]) <= b
&& Math.abs(arr[i] - arr[k]) <= c) {
count++;
}
}
}
}
return count;
}
public static void main(String[] args) {
CountGoodTriplets solution = new CountGoodTriplets();
int[] arr = {3, 0, 1, 1, 9, 7};
int a = 7, b = 2, c = 3;
System.out.println(solution.countGoodTriplets(arr, a, b, c)); // Output should be 4
}
}
Time Complexity: The time complexity of this solution is (O(n^3)), where (n) is the length of the array. Given the constraints, this is acceptable.
Space Complexity: The space complexity is (O(1)) since we are using only a few extra variables to store the count and index values.
This approach efficiently checks all possible triplets to ensure they meet the given conditions. Even though it’s a cubic time complexity brute force solution, it is sufficient for the problem constraints.
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?