Problem 395916 · medium · Phase 03 Linear Management & Searching

Distinct Pairs With a Fixed Difference

two pointers · sorting · deduplication

Given a list of integers nums and an integer k >= 0, return the number of distinct value pairs (a, b) such that both values occur in nums (at different indices) and b - a == k.

Examples

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

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

Constraints

  • 0 <= len(nums) <= 10**5, 0 <= k <= 10**7
  • Target: O(n log n) time for sorting then O(n) scanning, O(1) extra space beyond the sort.

Goals

  • Run two pointers in the same direction where the gap between them is the quantity of interest
  • Count value pairs rather than index pairs by skipping duplicates
Starting Python…