algoadvance

Leetcode 1534. Count Good Triplets

Problem Statement

Given an array of integers arr, and three integers a, b and c. You need to count the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:

  1. 0 <= i < j < k < arr.length
  2. |arr[i] - arr[j]| <= a
  3. |arr[j] - arr[k]| <= b
  4. |arr[i] - arr[k]| <= c

Return the number of good triplets.

Clarifying Questions

  1. What are the constraints on the length of the array and the values of a, b, and c?
    • Constraints:
      • 3 <= arr.length <= 100
      • 0 <= arr[i] <= 1000
      • 0 <= a, b, c <= 1000
  2. Can the array have duplicate values?
    • Yes, it can.
  3. What should be returned if no good triplets are found?
    • Return 0.

Strategy

  1. Brute Force Approach:
    • The simplest way to solve this problem is by checking every possible triplet in the array using three nested loops.
    • For each triplet, check if it satisfies all the given conditions.
    • If it does, increment the counter.
  2. Optimized Approach:
    • Given the constraints (array length up to 100), the brute force approach is feasible as it results in (O(n^3)) time complexity.
    • Therefore, using three nested loops to iterate through all possible triplets should work within the given limits.

Code

Here’s a straightforward implementation in Java using the brute force method:

public class CountGoodTriplets {
    public int countGoodTriplets(int[] arr, int a, int b, int c) {
        int count = 0;
        int n = arr.length;
        
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                for (int k = j + 1; k < n; 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;
    }

    public static void main(String[] args) {
        CountGoodTriplets solution = new CountGoodTriplets();
        int[] arr = {3, 0, 1, 1, 9, 7};
        int a = 7, b = 2, c = 3;
        System.out.println(solution.countGoodTriplets(arr, a, b, c)); // Output should be 4
    }
}

Time Complexity

This approach efficiently checks all possible triplets to ensure they meet the given conditions. Even though it’s a cubic time complexity brute force solution, it is sufficient for the problem constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI