Problem 1534

Abstract / Summary

Count the number of triplets where each pair of elements meets given conditions for being good.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
15 lines | 507 bytes | submitted November 1, 2023 | GitHub   9% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Enumeration
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 arr is empty or contains fewer than three elements, the range expressions in the loops produce empty sequences, so the body never runs and the method returns 0.
  • 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, or c are 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.35 | σ = 1.59

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
31 links | 18 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   November 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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