![]() |
VOOZH | about |
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].
Table of Content
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.
4
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.
4
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:
- (arr[i] - complement) is positive:
- arr[i] - complement = k
- So, complement = arr[i] - k
- (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.
4