Skip to content
BytePatterns

Count Pairs With a Given Gap

EasyHash Tables#hash-map#complement-lookup~15m

Problem

A pricing team wants to know how many distinct price pairs in a list differ by exactly k. Given a list of integers nums and an integer k ≥ 0, return the number of distinct value pairs (a, b) with a ≤ b, both present in the list, and b - a = k. A pair with k = 0 needs the value to appear at least twice. The list has up to 10,000 values, so compare against a lookup table rather than every other value.

Examples

Input:  nums = [3, 1, 4, 1, 5], k = 2
Output: 2
Why:    (1, 3) and (3, 5); the second 1 does not make a new pair
Input:  nums = [1, 2, 3, 4, 5], k = 1
Output: 4
Input:  nums = [1, 3, 1, 5, 4], k = 0
Output: 1
Why:    edge case, only 1 appears twice

Hints

0 / 3

Stuck on the idea rather than the code? Two Sum covers it.