Pairs With Difference

Hashmap Array Pairs Medium

Problem: Pairs With Difference

Given an array of integers and an integer k, write a function that returns the count of unique pairs (x, y) such that the absolute difference between x and y is exactly k. Each pair should be counted only once, and the order of the numbers in the pair does not matter (i.e., (x, y) is considered the same as (y, x)).

Example

For example, given the array: [1, 5, 3, 4, 2] and k = 2, the unique pairs with an absolute difference of 2 are:

  • (1, 3)
  • (3, 5)
  • (4, 2)

Your function should return 3.

Constraints

  • The array may contain duplicate elements; however, each unique pair should be counted only once.
  • The value of k will be a non-negative integer.
  • Aim for an efficient solution with a time complexity better than O(n^2) by utilizing hashmap tricks.

Bonus Connection

Today, on February 11th, we remember historical innovators who transformed the world with creative problem-solving. Use your creativity to solve this problem efficiently!

Function Signature

Your function should have the following signature (or equivalent in your chosen language):

function pairsWithDifference(arr, k) // returns an integer

Happy coding!