KatInterview

Count Close Triplets Within a Value Range

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingsliding-windowsortingcombinatorics

Last updated

Tests sorting, sliding window, and combinatorial counting to find how many index-distinct triplets fit within a given value spread.

You are building a quality-control tool for a network of weather stations. Each station reports a single numeric measurement. To flag unreliable batches, you need to count how many triplets of stations are close to one another.

A triplet is any selection of three distinct positions i < j < k from the list of measurements. A triplet is close when the difference between its largest and smallest values is at most gap (inclusive).

Write a function that returns the total number of close triplets.

Important notes

  • Positions are what make two triplets different, not values. Two stations that happen to report the same measurement are still two separate stations.
  • A triplet where all three values are identical has a spread of 0, which satisfies any non-negative gap.
  • If the list contains fewer than three measurements, the answer is 0.
  • The answer may be very large (up to roughly 1.67 × 10¹⁴ for the largest inputs), so use a 64-bit integer accumulator if you are working in a fixed-width language.

Constraints

  • 0 <= len(measurements) <= 10^5
  • 0 <= measurements[i] <= 10^9
  • 0 <= gap <= 10^9
  • An O(n²) or O(n³) solution will time out. Aim for O(n log n).

Examples

Example 1

Input: count_close_triplets([10, 14, 11, 19, 12], 2)

Output: 1

Example 2

Input: count_close_triplets([5, 5, 6, 5, 9], 1)

Output: 4

Example 3

Input: count_close_triplets([3, 8], 100)

Output: 0

Hints

Hint 1

The order of positions does not affect whether a triplet is close — only the three values matter. What does that let you do to simplify the search?

Hint 2

After sorting, the minimum and maximum of any three consecutive candidates are just the endpoints of the subarray they span. Try fixing the rightmost element and asking: how far left can the window reach?

Hint 3

If there are m elements to the left of the current rightmost element that all fall within the gap, how many pairs can you choose from those m elements to complete a triplet? You do not need an inner loop — a direct formula works.