Skip to content
EasyArraysAI interview only

Count Good Triplets

Asked atamazongooglemicrosoft

01 · Problem

You are given an integer array arr and three non-negative integers a, b and c. A triplet of indices (i, j, k) is good when 0 <= i < j < k < arr.length and all three conditions hold:

  • |arr[i] - arr[j]| <= a
  • |arr[j] - arr[k]| <= b
  • |arr[i] - arr[k]| <= c

Return the number of good triplets. Triplets are counted by index, so equal values at different positions form different triplets. Return 0 if none exist.

02 · Examples

Example 01
Input
arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3
Output
4

The good triplets by value are (3,0,1), (3,0,1), (3,1,1) and (0,1,1).

Example 02
Input
arr = [1,1,2,2,3], a = 0, b = 0, c = 1
Output
0

Every pair must be equal in the first two conditions, and no value appears three times, so no triplet qualifies.

Example 03
Input
arr = [2,4,1,5], a = 2, b = 3, c = 3
Output
2

The good triplets by value are (2,4,1), (2,4,5).

03 · Constraints

  • 013 <= arr.length <= 100
  • 020 <= arr[i] <= 1000
  • 030 <= a, b, c <= 1000

04 · Optimal complexity

Time
O(n^3)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.