Skip to content

Commit 038e074

Browse files
committed
Sync LeetCode submission Runtime - 300 ms (40.32%), Memory - 17.9 MB (24.73%)
1 parent 1c3b858 commit 038e074

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

1656-count-good-triplets/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<p>Given an array of integers <code>arr</code>, and three integers&nbsp;<code>a</code>,&nbsp;<code>b</code>&nbsp;and&nbsp;<code>c</code>. You need to find the number of good triplets.</p>
2+
3+
<p>A triplet <code>(arr[i], arr[j], arr[k])</code>&nbsp;is <strong>good</strong> if the following conditions are true:</p>
4+
5+
<ul>
6+
<li><code>0 &lt;= i &lt; j &lt; k &lt;&nbsp;arr.length</code></li>
7+
<li><code>|arr[i] - arr[j]| &lt;= a</code></li>
8+
<li><code>|arr[j] - arr[k]| &lt;= b</code></li>
9+
<li><code>|arr[i] - arr[k]| &lt;= c</code></li>
10+
</ul>
11+
12+
<p>Where <code>|x|</code> denotes the absolute value of <code>x</code>.</p>
13+
14+
<p>Return<em> the number of good triplets</em>.</p>
15+
16+
<p>&nbsp;</p>
17+
<p><strong class="example">Example 1:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
21+
<strong>Output:</strong> 4
22+
<strong>Explanation:</strong>&nbsp;There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].
23+
</pre>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<pre>
28+
<strong>Input:</strong> arr = [1,1,2,2,3], a = 0, b = 0, c = 1
29+
<strong>Output:</strong> 0
30+
<strong>Explanation: </strong>No triplet satisfies all conditions.
31+
</pre>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>3 &lt;= arr.length &lt;= 100</code></li>
38+
<li><code>0 &lt;= arr[i] &lt;= 1000</code></li>
39+
<li><code>0 &lt;= a, b, c &lt;= 1000</code></li>
40+
</ul>

1656-count-good-triplets/solution.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Approach 1: Enumeration
2+
3+
# Time: O(n ^ 3)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
8+
n = len(arr)
9+
count = 0
10+
11+
for i in range(n):
12+
for j in range(i + 1, n):
13+
for k in range(j + 1, n):
14+
if (
15+
abs(arr[i] - arr[j]) <= a and
16+
abs(arr[j] - arr[k]) <= b and
17+
abs(arr[i] - arr[k]) <= c
18+
):
19+
count += 1
20+
return count
21+
22+

0 commit comments

Comments
 (0)