Pairs With Difference

Hashmap Arrays Hashmap Tricks Medium Coding Problem

Problem Description

Given an array of integers and an integer k, write a function to return the number of unique pairs (a, b) such that the absolute difference between a and b is exactly k (i.e., |a - b| = k). Each pair (a, b) should be counted only once and the pair (a, b) is considered the same as (b, a).

Example

Input: nums = [1, 7, 5, 9, 2, 12, 3], k = 2
Output: 4

Explanation: The 4 unique pairs are (1, 3), (3, 5), (5, 7), (7, 9).

Constraints

  • It is guaranteed that the array length is at most 10^5.
  • k is a non-negative integer.

Hint

Use a hashmap (or dictionary) to store the frequency of each number in the array to help achieve an efficient solution. This approach can help you search for the complement efficiently.

Happy coding on this fine May 2, 2025 – a great day to apply some clever hashmap tricks!