Count Good Triplets — LeetCode 1534 Python Solution

EasyArrayEnumeration
Problem
#1534
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n^3), where n is the length of the array \textit{arr}
SpaceO(1) auxiliary

Related problems

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview