Count Close Triplets Within a Value Range
Arrays & HashingAuto-graded · 23 test casesLast 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-negativegap. - 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^50 <= measurements[i] <= 10^90 <= 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
Whether a triplet is close depends only on its three values, not on the original positions. Sorting the list preserves the total number of valid triplets: every index-triplet maps to a unique position-triplet in the sorted array, so the count is unchanged. After sorting, the spread of any contiguous window is simply values[right] - values[left].
Fix the rightmost element, count pairs to its left
Iterate through the sorted array and treat each index right as the maximum of every triplet it anchors. A triplet is close when values[right] - values[left] <= gap. Because the array is sorted, all valid partners for right form a contiguous prefix ending at right - 1. Maintain a pointer left that marks where this valid window begins.
If the window [left, right - 1] contains m = right - left elements, the number of ways to pick two of them to complete the triplet is C(m, 2) = m * (m - 1) // 2. Each triplet is counted exactly once — at the step where right equals the triplet's largest position.
Two-pointer sweep
As right advances, values[right] never decreases, so left never needs to move backward. Advancing left only forward gives an O(n) sweep after the initial sort.
Why edge cases need no special handling
- Fewer than 3 elements:
mis at most 1 for everyright, soC(m, 2) = 0throughout. gap = 0: only runs of equal values contribute. A run of lengthcproducesC(c, 3)triplets, which the formula reproduces naturally.- Duplicate values: they occupy distinct positions in the sorted array and are handled without any extra logic.
Complexity
- Time: O(n log n) for sorting + O(n) for the two-pointer sweep = O(n log n) overall.
- Space: O(n) for the sorted copy (O(1) extra if you sort in place).
Alternative
bisect_left can replace the moving pointer: for each right, binary-search for the leftmost index where values[right] - values[l] <= gap. This is also O(n log n) and is a valid approach to discuss in an interview.
Walkthrough on example 1
measurements = [10, 14, 11, 19, 12], gap = 2
Sorted: [10, 11, 12, 14, 19]
| right | value | left | m | C(m,2) |
|---|---|---|---|---|
| 0 | 10 | 0 | 0 | 0 |
| 1 | 11 | 0 | 1 | 0 |
| 2 | 12 | 0 | 2 | 1 |
| 3 | 14 | 2 | 1 | 0 |
| 4 | 19 | 4 | 0 | 0 |
Total = 1.
from typing import List
def count_close_triplets(measurements: List[int], gap: int) -> int:
values = sorted(measurements)
left = 0
total = 0
for right, value in enumerate(values):
while value - values[left] > gap:
left += 1
count = right - left
total += count * (count - 1) // 2
return total