FastPrepCount Triplets Within a Value Range

Count Triplets Within a Value Range

IBM logoIBM● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an integer array values and a nonnegative integer d, count index triplets i < j < k for which the difference between the maximum and minimum selected values is at most d.

Return the number of qualifying index triplets. Equal values at different indices are distinct choices.

Function

countBoundedTriplets(values: int[], d: int) → long

Examples

Example 1

values = [1,2,3,4]d = 2return = 2

The qualifying value groups use indices for [1,2,3] and [2,3,4].

Example 2

values = [1,1,1,1]d = 0return = 4

All four choices of three indices have range zero.

Example 3

values = [1,5,9]d = 3return = 0

The only triplet has range 8, which exceeds d.

Constraints

  • 3 <= values.length <= 200000.
  • -10^9 <= values[i] <= 10^9.
  • 0 <= d <= 2 * 10^9.
  • The answer fits in a signed 64-bit integer.

More IBM problems

See IBM hiring insights
public long countBoundedTriplets(int[] values, int d) {
    // Write your code here.
}
values[1,2,3,4]
d2
expected2
Checking account…