Python 1534.py
class Solution:
def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
result = 0
# dumb and short solution
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if abs(arr[i] - arr[j]) > a:
continue
for k in range(j + 1, len(arr)):
if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
result += 1
return result
Difficulty
and has an acceptance rate of about 86% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Enumeration
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method countGoodTriplets that receives an integer list arr and three non-negative thresholds a, b, and c. The method returns the number of index triples (i, j, k) with i < j < k that satisfy three absolute-difference constraints:
|arr[i] - arr[j]| ≤ a|arr[j] - arr[k]| ≤ b|arr[i] - arr[k]| ≤ c
The implementation follows a straightforward triple-nested loop structure, incrementing a counter whenever a triplet meets all three conditions.
Key Steps
The algorithm can be broken down into three distinct phases, each reflected by a loop in the source code.
Outer Loop - Selecting the First Index
for i in range(len(arr)):
The outermost loop iterates over every possible position for the first element of a triplet. By using range(len(arr)), the loop automatically adapts to the length of the input list, and when the list contains fewer than three elements the loop body never executes, resulting in a return value of 0.
Middle Loop - Selecting the Second Index and Early Pruning
for j in range(i + 1, len(arr)):
if abs(arr[i] - arr[j]) > a:
continue
For each i, the middle loop chooses a subsequent index j. The conditional check abs(arr[i] - arr[j]) > a acts as an early-exit guard: if the first constraint is already violated, the loop skips the inner work for that j. This pruning prevents unnecessary evaluation of the innermost loop when the pair (i, j) cannot possibly belong to a valid triplet.
Inner Loop - Selecting the Third Index and Final Validation
for k in range(j + 1, len(arr)):
if abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
result += 1
The innermost loop enumerates every index k that follows j. Within this loop the remaining two constraints are tested simultaneously. When both conditions hold, the counter result is incremented, indicating that a “good” triplet has been found.
Edge Cases Handled
The code gracefully handles several boundary situations without additional logic:
- Empty or Very Small Input - If
arris empty or contains fewer than three elements, the range expressions in the loops produce empty sequences, so the body never runs and the method returns0. - Identical Elements - When all elements are equal, the absolute differences are zero, which always satisfies the three thresholds (provided they are non-negative). The loops will count every possible combination of three indices.
- Large Threshold Values - If any of the thresholds
a,b, orcare larger than the maximum possible difference in the array, the corresponding condition will never reject a pair, allowing the loops to explore all index combinations. - Threshold Zero - When a threshold is zero, the associated condition reduces to an equality check (
abs(x - y) == 0). The code correctly filters out any pair that does not consist of identical values.
Performance Optimizations Observed
Although the algorithm follows a naïve triple-nested enumeration, it incorporates a small but effective optimization: the early continue in the middle loop. By checking the first constraint before entering the innermost loop, the implementation avoids the cost of evaluating the two remaining constraints for every possible k. This short-circuiting can lead to a noticeable reduction in total iterations, especially when a is small relative to the spread of values in arr.
Another implicit optimization stems from the use of range and direct indexing (arr[i], arr[j], arr[k]). This avoids the overhead of creating intermediate slices or iterator objects, keeping the inner loop body tight and cache-friendly.
Overall, the method delivers a clear, deterministic count of qualifying triplets while employing early pruning to limit unnecessary work.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered building blocks lined up on the floor. Each block has a special number painted on it. To find the special groups, think of picking three blocks at a time, moving from the left side of the row toward the right.
First, imagine choosing the first block and the second block a little bit ahead of it. You check if the difference between their numbers is small enough. If the numbers are too far apart, you skip those two and move to the next pair.
If the first two blocks are close enough, you look for a third block further down the line. You check this third block against the second block to see if they are friends, and then you check it against the first block to see if they are also friends. If all three blocks pass the tests, it means you found a perfect set. You keep a running count of every perfect set you find as you move down the line until you have checked every combination.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | Java | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | Java | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 1995: Count Special Quadruplets
Solved On The Same Day
- problem 897: Increasing Order Search Tree
- problem 1222: Queens That Can Attack the King
- problem 1418: Display Table of Food Orders in a Restaurant
- problem 1525: Number of Good Ways to Split a String
- problem 2265: Count Nodes Equal to Average of Subtree
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality