Problem 255646 · medium · Phase 02 Linear Data Structures

Distinct Pairs With Difference k

hash maps · sets · pair counting

Given nums and a non-negative integer k, count the distinct value pairs (x, y) such that both x and y occur in nums and y - x == k. Pairs are unordered and counted once no matter how many times the values repeat. When k == 0, a pair (x, x) counts only if x occurs at least twice.

Examples

Input:  nums = [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: value pairs (1, 3) and (3, 5).

Input:  nums = [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: only the value 1 repeats.

Constraints

  • 0 <= len(nums) <= 10**5, 0 <= k <= 10**9
  • Target complexity: O(n) time.

Goals

  • Count pairs by value rather than by index
  • Treat k = 0 as a special case
Starting Python…