Count Good Triplets

Given an array of integers arr and three integers a, b and c, count the good triplets. A triplet (arr[i], arr[j], arr[k]) is good when 0 <= i < j < k < arr.length, |arr[i] - arr[j]| <= a, |arr[j] - arr[k]| <= b and |arr[i] - arr[k]| <= c. Return the number of good triplets.

30:00

Count Good Triplets
easy
Free written solution
Topics
Companies

Given an array of integers arr and three integers a, b and c, count the good triplets. A triplet (arr[i], arr[j], arr[k]) is good when 0 <= i < j < k < arr.length, |arr[i] - arr[j]| <= a, |arr[j] - arr[k]| <= b and |arr[i] - arr[k]| <= c. Return the number of good triplets.

Example 1:
Input: {"arr":[3,0,1,1,9,7],"a":7,"b":2,"c":3}
Output: 4
Constraints:
  • 3≤arr.length≤1003 \leq \text{arr.length} \leq 100

  • 0≤arr[i]≤10000 \leq \text{arr}[i] \leq 1000

  • 0≤a,b,c≤10000 \leq a, b, c \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[3,0,1,1,9,7],"a":7,"b":2,"c":3}

Try every i < j < k. A triplet is good when the i-j gap is at most a = 7, the j-k gap at most b = 2 and the i-k gap at most c = 3.

300112139475

|arr[i, j]|

· ≤ 7

a

|arr[j, k]|

· ≤ 2

b

|arr[i, k]|

· ≤ 3

c

count

0

no good triplet yet

Variables
VariableValue
count0
DepthFunction Call
Stack empty
0/33