LeetCode 1534: Count Good Triplets Solution

Master LeetCode problem 1534 (Count Good Triplets), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1534. Count Good Triplets

Problem Explanation

Explanation

To solve this problem, we can iterate through all possible triplets (i, j, k) satisfying the given conditions and count the number of good triplets. We can use three nested loops to iterate through all possible combinations of indices i, j, k. Then, we check if the conditions are satisfied for each triplet and increment the count if it is a good triplet.

Algorithm:

  1. Initialize a variable count to store the number of good triplets.
  2. Iterate over all possible triplets (i, j, k) where 0 <= i < j < k < arr.length.
  3. Check if the conditions are satisfied: |arr[i] - arr[j]| <= a, |arr[j] - arr[k]| <= b, and |arr[i] - arr[k]| <= c.
  4. If the conditions are satisfied, increment count.
  5. Return the final count as the result.

Time Complexity:

The time complexity of this algorithm is O(n^3), where n is the length of the input array arr.

Space Complexity:

The space complexity of this algorithm is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public int countGoodTriplets(int[] arr, int a, int b, int c) {
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                for (int k = j + 1; k < arr.length; k++) {
                    if (Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) {
                        count++;
                    }
                }
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1534 (Count Good Triplets)?

This page provides optimized solutions for LeetCode problem 1534 (Count Good Triplets) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1534 (Count Good Triplets)?

The time complexity for LeetCode 1534 (Count Good Triplets) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1534 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1534 in Java, C++, or Python.

Back to LeetCode Solutions