VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-difference-equal-k/

⇱ Count pairs with absolute difference equal to k - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count pairs with absolute difference equal to k

Last Updated : 23 Jul, 2025

Given an array arr[] and a positive integer k, the task is to count all pairs (i, j) such that i < j and absolute value of (arr[i] - arr[j]) is equal to k

Examples:

Input: arr[] = [1, 4, 1, 4, 5], k = 3
Output: 4
Explanation: There are 4 pairs with absolute difference 3, the pairs are [1, 4], [1, 4], [1, 4] and [4, 1]

Input: arr[] = [8, 16, 12, 16, 4, 0], k = 4
Output: 5
Explanation: There are 5 pairs with absolute difference 4, the pairs are [8, 12], [8, 4], [16, 12], [12, 16], [4, 0].

[Naive Approach] Generating all pairs - O(n^2) Time and O(1) Space

The basic idea is to use two nested loops to generate all pairs in arr[]. For each pair, if the absolute difference is equal to k, increment the count by 1.


Output
4

[Better Approach] Sorting and Two Pointer Technique - O(n*logn) Time and O(1) Space

The idea is to first sort the array and then use the two-pointer technique by maintaining two pointers, say i and j and initialize them to the beginning of the array. According to the sum of the elements, we can have three cases:

  • arr[i] - arr[j] < target: We need to increase the difference between the elements, move the j pointer towards right.
  • arr[i] - arr[j] > target: We need to decrease the difference between the elements, move the i pointer towards right.
  • arr[i] - arr[j] = target: We have found a pair whose difference is equal to target. We can find the product of the count of both the elements and add them to the result.

Output
4

[Expected Approach] Using Hash Map or Dictionary – O(n) Time and O(n) Space

The idea is to count the frequency of each number in a hash map or dictionary as we go through the array Iterate over the array and for each element arr[i], we need another element say complement such that abs(arr[i] - complement) = k. Now, we can have two cases:

  1. (arr[i] - complement) is positive:
    • arr[i] - complement = k
    • So, complement = arr[i] - k
  2. (arr[i] - complement) is negative:
    • (arr[i] - complement) = -k
    • So, complement = arr[i] + k

So for each element arr[i], we can check if complement (arr[i] + k) or (arr[i] - k) is present in the hash map. If it is, increment the count variable by the occurrences of complement in map.


Output
4


Comment