Count Good Triplets — LeetCode 1534 Python Solution
EasyArrayEnumeration
- Problem
- #1534
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n^3), where n is the length of the array \textit{arr} |
| Space | O(1) auxiliary |
Related problems
LeetCode 2179Count Good Triplets in an ArrayHardLeetCode 1566Detect Pattern of Length M Repeated K or More TimesEasyLeetCode 1620Coordinate With Maximum Network QualityMediumLeetCode 2735Collecting ChocolatesMediumLeetCode 2765Longest Alternating SubarrayEasyLeetCode 2778Sum of Squares of Special ElementsEasy
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(n^3), 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.