Skip to main content
Back to problems
#1534
Easy Algorithms

Count good triplets

Array Enumeration
85.5% acceptance
Feb 25, 2026
1202
1250
Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets. A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true: 0 <= i < j < k < arr.length |arr[i] - arr[j]| <= a |arr[j] - arr[k]| <= b |arr[i] - arr[k]| <= c

Solution

Rust
Time O(n³)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_good_triplets(arr: Vec<i32>, a: i32, b: i32, c: i32) -> i32 {
    let n = arr.len();
    let mut count = 0;
    for i in 0..n {
      for j in i+1..n {
        if (arr[i] - arr[j]).abs() > a { continue; }
        for k in j+1..n {
          if (arr[j] - arr[k]).abs() <= b && (arr[i] - arr[k]).abs() <= c {
            count += 1;
          }
        }
      }
    }
    count
  }
}