EasyNo. 1534
Count Good Triplets — LeetCode 1534 Python Solution
- Topics
- Array, Enumeration
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.
Example
- Input
- arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
- Output
- 4
- Explanation
- There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
Python solution
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
ans, n = 0, len(arr)
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
ans += (
abs(arr[i] - arr[j]) <= a
and abs(arr[j] - arr[k]) <= b
and abs(arr[i] - arr[k]) <= c
)
return ansComplexity
- Time
- O(n3)where n is the length of the array arr
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2179 | Count Good Triplets in an Array | Hard |
| 1566 | Detect Pattern of Length M Repeated K or More Times | Easy |
| 1620 | Coordinate With Maximum Network Quality | Medium |
| 2735 | Collecting Chocolates | Medium |
| 2765 | Longest Alternating Subarray | Easy |
| 2778 | Sum of Squares of Special Elements | Easy |
Frequently asked questions
- How hard is LeetCode 1534. Count Good Triplets?
LeetCode 1534. Count Good Triplets is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1534. Count Good Triplets?
The Python solution on this page runs in O(n3), where n is the length of the array \textit{arr}.
- What is the space complexity of LeetCode 1534. Count Good Triplets?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1534. Count Good Triplets cover?
LeetCode 1534. Count Good Triplets is tagged Array and Enumeration on LeetCode.