KatInterview

Count Valid Number Triplets Within Range

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingtwo-pointerscombinatorics

Last 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) <= 100000
  • 0 <= numbers[i] <= 10^9
  • 0 <= 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.