#1534
Count Good Triplets
EasyApproaches
💡
Intuition
Time O(n²)Space O(1)
The brute force approach involves checking every possible triplet in the array to see if it meets the conditions of being a good triplet. Given the constraints, this method is straightforward and will work within the limits.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter to zero for counting good triplets.
- 2Step 2: Use three nested loops to iterate through all possible triplets (i, j, k) such that 0 <= i < j < k < arr.length.
- 3Step 3: For each triplet, check if the conditions |arr[i] - arr[j]| <= a, |arr[j] - arr[k]| <= b, and |arr[i] - arr[k]| <= c are satisfied. If they are, increment the counter.
- 4Step 4: Return the counter after checking all triplets.
solution.py9 lines
1def countGoodTriplets(arr, a, b, c):
2 count = 0
3 n = len(arr)
4 for i in range(n):
5 for j in range(i + 1, n):
6 for k in range(j + 1, n):
7 if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
8 count += 1
9 return countℹ
Complexity note: The time complexity is O(n²) because we are using three nested loops to iterate through the array, where n is the length of the array. The space complexity is O(1) since we are using a constant amount of extra space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.