Count Valid Number Triplets Within Range
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Find how many ways to pick three numbers from an array where the maximum minus the minimum stays within a given threshold.
You are given an array of integers numbers and a non-negative integer threshold. Your task is to count how many ways you can select three distinct elements from the array such that the difference between the largest and smallest selected values does not exceed threshold.
More formally, for any three distinct indices i, j, k (where 0 <= i, j, k < len(numbers) and i, j, k are all different), define the range of this triplet as:
max(numbers[i], numbers[j], numbers[k]) - min(numbers[i], numbers[j], numbers[k])
A triplet is valid if its range is at most threshold.
Return the total count of valid triplets.
Important: Triplets are distinguished by their index positions, not by their values. If two sets of three indices contain different positions, they count as separate triplets even if the values at those positions are identical.
Constraints
0 <= len(numbers) <= 1000000 <= numbers[i] <= 10^90 <= threshold <= 10^9- If the array has fewer than three elements, return
0 - The result may exceed 32-bit integer range; use appropriate data types
Examples
Example 1
Input: count_valid_triplets([50, 52, 54, 56, 58], 4)
Output: 3
Example 2
Input: count_valid_triplets([80, 30, 30, 60, 45], 15)
Output: 1
Example 3
Input: count_valid_triplets([99, 99, 99, 99], 0)
Output: 4
Hints
Hint 1
Consider how sorting the array might simplify the problem without changing the answer.
Hint 2
For each element as the maximum of a triplet, how can you efficiently count how many valid pairs exist among the smaller elements?
Hint 3
A two-pointer technique can help you avoid checking all possible pairs for each position.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that sorting the array preserves the count of valid triplets while making them easier to identify. Since we only care about the values in each triplet (not their original positions), and we're counting combinations of positions, sorting creates a one-to-one mapping that doesn't change the answer.
Once sorted, we can process each position as the potential maximum element of valid triplets. For position right with value sorted_nums[right], we need to find all pairs of smaller elements whose minimum value is within threshold of this maximum.
In a sorted array, all valid smaller elements form a contiguous segment from some index left up to right - 1. The leftmost valid index left is where sorted_nums[left] + threshold >= sorted_nums[right], or equivalently, sorted_nums[right] - sorted_nums[left] <= threshold.
If there are m valid elements in the range [left, right-1], we can choose any 2 of them to pair with sorted_nums[right], giving us C(m, 2) = m × (m-1) / 2 valid triplets.
The optimization comes from the two-pointer technique: as right increases, the maximum value never decreases, so left never needs to move backward. We maintain left as a sliding pointer that only advances, giving us linear time after sorting.
Why This Works
Every valid triplet has exactly one maximum element. By crediting each triplet to its maximum position and summing over all positions, we count each triplet exactly once. The formula m × (m-1) / 2 correctly handles all cases including duplicates—if multiple elements have the same value, they're treated as distinct positions in the count.
Complexity
- Time: O(n log n) for sorting, plus O(n) for the two-pointer traversal, giving O(n log n) overall
- Space: O(n) for the sorted copy of the array
Implementation
from typing import List
def count_valid_triplets(numbers: List[int], threshold: int) -> int:
n = len(numbers)
if n < 3:
return 0
sorted_nums = sorted(numbers)
result = 0
left = 0
for right in range(n):
max_val = sorted_nums[right]
while sorted_nums[left] + threshold < max_val:
left += 1
eligible = right - left
result += eligible * (eligible - 1) // 2
return result