Problem 255646 · medium · Level 02 Linear Data Structures

Price Tags Exactly k Apart

hash maps · sets · pair counting

A shop's price list nums may contain the same price several times. A customer wants two items whose prices differ by exactly k (a non-negative integer). Count the different pairs of prices (x, y) with y - x == k she could choose, where both prices occur in nums. A pair of prices counts once however many items carry them, and the order inside a pair does not matter. When k == 0, the pair (x, x) needs at least two items priced x.

Examples

Input:  nums = [6, 2, 9, 2, 4], k = 2
Output: 2
Explanation: value pairs (2, 4) and (4, 6); the second 2 adds nothing new.

Input:  nums = [5, 2, 7, 7, 3, 5, 5], k = 0
Output: 2
Explanation: the values 7 and 5 repeat; three copies of 5 still count once.

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…