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.
C++
// C++ Program to count all pairs with difference equal to k
// by generating all pairs
#include <iostream>
#include <vector>
using namespace std;
int countPairs(vector<int> &arr, int k) {
int n = arr.size();
int cnt = 0;
// generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If absolute difference = k, then increment
// count by 1
if (abs(arr[i] - arr[j]) == k) {
cnt += 1;
}
}
}
return cnt;
}
int main() {
vector<int> arr = {1, 4, 1, 4, 5};
int k = 3;
cout << countPairs(arr, k);
return 0;
}
C
// C Program to count all pairs with difference equal to k
// by generating all pairs
#include <stdio.h>
int countPairs(int arr[], int n, int k) {
int cnt = 0;
// generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If absolute difference = k, then increment
// count by 1
if (abs(arr[i] - arr[j]) == k) {
cnt += 1;
}
}
}
return cnt;
}
int main() {
int arr[] = {1, 4, 1, 4, 5};
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", countPairs(arr, n, k));
return 0;
}
Java
// Java Program to count all pairs with difference equal to k
// by generating all pairs
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.length;
int cnt = 0;
// generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If absolute difference = k, then increment
// count by 1
if (Math.abs(arr[i] - arr[j]) == k) {
cnt += 1;
}
}
}
return cnt;
}
public static void main(String[] args) {
int[] arr = {1, 4, 1, 4, 5};
int k = 3;
System.out.println(countPairs(arr, k));
}
}
Python
# Python Program to count all pairs with difference equal to k
# by generating all pairs
def countPairs(arr, k):
n = len(arr)
cnt = 0
# generate all possible pairs
for i in range(n):
for j in range(i + 1, n):
# If absolute difference = k, then increment
# count by 1
if abs(arr[i] - arr[j]) == k:
cnt += 1
return cnt
if __name__ == "__main__":
arr = [1, 4, 1, 4, 5]
k = 3
print(countPairs(arr, k))
C#
// C# Program to count all pairs with difference equal to k
// by generating all pairs
using System;
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.Length;
int cnt = 0;
// generate all possible pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If absolute difference = k, then increment
// count by 1
if (Math.Abs(arr[i] - arr[j]) == k) {
cnt += 1;
}
}
}
return cnt;
}
static void Main() {
int[] arr = {1, 4, 1, 4, 5};
int k = 3;
Console.WriteLine(countPairs(arr, k));
}
}
JavaScript
// JavaScript Program to count all pairs with difference equal
// to k by generating all pairs
function countPairs(arr, k) {
const n = arr.length;
let cnt = 0;
// generate all possible pairs
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// If absolute difference = k, then increment
// count by 1
if (Math.abs(arr[i] - arr[j]) === k) {
cnt += 1;
}
}
}
return cnt;
}
// Driver Code
const arr = [1, 4, 1, 4, 5];
const k = 3;
console.log(countPairs(arr, k));
[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.
C++
// C++ Program to count all pairs with difference equal to k
// using Two Pointer Technique
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int countPairs(vector<int> &arr, int k) {
int n = arr.size();
int cnt = 0;
sort(arr.begin(), arr.end());
int i = 0, j = 0;
while(j < n) {
// If the difference is greater than k, increase
// the difference by moving pointer j towards right
if(arr[j] - arr[i] < k)
j++;
// If difference is greater than k, decrease the
// difference by moving pointer i towards right
else if(arr[j] - arr[i] > k)
i++;
// If difference is equal to k, count all such pairs
else {
int ele1 = arr[i], ele2 = arr[j];
int cnt1 = 0, cnt2 = 0;
// Count frequency of first element of the pair
while(j < n && arr[j] == ele2) {
j++;
cnt2++;
}
// Count frequency of second element of the pair
while(i < n && arr[i] == ele1) {
i++;
cnt1++;
}
// If both the elements are same, then count of
// pairs = the number of ways to choose 2
// elements among cnt1 elements
if(ele1 == ele2)
cnt += (cnt1 * (cnt1 - 1))/2;
// If the elements are different, then count of
// pairs = product of the count of both elements
else
cnt += (cnt1 * cnt2);
}
}
return cnt;
}
int main() {
vector<int> arr = {1, 4, 1, 4, 5};
int k = 3;
cout << countPairs(arr, k);
return 0;
}
C
// C Program to count all pairs with difference equal to k
// using Two Pointer Technique
#include <stdio.h>
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int countPairs(int arr[], int n, int k) {
int cnt = 0;
qsort(arr, n, sizeof(int), compare);
int i = 0, j = 0;
while (j < n) {
if (arr[j] - arr[i] < k)
j++;
// If difference is greater than k, decrease the
// difference by moving i pointer towards right
else if (arr[j] - arr[i] > k)
i++;
// If difference is equal to k, increase the difference
// by moving j pointer towards right
else {
int ele1 = arr[i], ele2 = arr[j];
int cnt1 = 0, cnt2 = 0;
// Count frequency of first element of the pair
while (j < n && arr[j] == ele2) {
j++;
cnt2++;
}
// Count frequency of second element of the pair
while (i < n && arr[i] == ele1) {
i++;
cnt1++;
}
// If both the elements are same, then count of
// pairs = the number of ways to choose 2
// elements among cnt1 elements
if (ele1 == ele2)
cnt += (cnt1 * (cnt1 - 1)) / 2;
// If the elements are different, then count of
// pairs = product of the count of both elements
else
cnt += (cnt1 * cnt2);
}
}
return cnt;
}
int main() {
int arr[] = {1, 4, 1, 4, 5};
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", countPairs(arr, n, k));
return 0;
}
Java
// Java Program to count all pairs with difference equal to k
// using Two Pointer Technique
import java.util.Arrays;
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.length;
int cnt = 0;
Arrays.sort(arr);
int i = 0, j = 0;
while (j < n) {
if (arr[j] - arr[i] < k)
j++;
// If difference is greater than k, decrease the
// difference by moving i pointer towards right
else if (arr[j] - arr[i] > k)
i++;
// If difference is equal to k, increase the difference
// by moving j pointer towards right
else {
int ele1 = arr[i], ele2 = arr[j];
int cnt1 = 0, cnt2 = 0;
// Count frequency of first element of the pair
while (j < n && arr[j] == ele2) {
j++;
cnt2++;
}
// Count frequency of second element of the pair
while (i < n && arr[i] == ele1) {
i++;
cnt1++;
}
// If both the elements are same, then count of
// pairs = the number of ways to choose 2
// elements among cnt1 elements
if (ele1 == ele2)
cnt += (cnt1 * (cnt1 - 1)) / 2;
// If the elements are different, then count of
// pairs = product of the count of both elements
else
cnt += (cnt1 * cnt2);
}
}
return cnt;
}
public static void main(String[] args) {
int[] arr = {1, 4, 1, 4, 5};
int k = 3;
System.out.println(countPairs(arr, k));
}
}
Python
# Python Program to count all pairs with difference equal to k
# using Two Pointer Technique
def countPairs(arr, k):
n = len(arr)
cnt = 0
arr.sort()
i = 0
j = 0
while j < n:
# If the difference is greater than k, increase
# the difference by moving j pointer towards right
if arr[j] - arr[i] < k:
j += 1
# If difference is greater than k, decrease the
# difference by moving i pointer towards right
elif arr[j] - arr[i] > k:
i += 1
# If difference is equal to k, count all such pairs
else:
ele1 = arr[i]
ele2 = arr[j]
cnt1 = 0
cnt2 = 0
# Count frequency of first element of the pair
while j < n and arr[j] == ele2:
j += 1
cnt2 += 1
# Count frequency of second element of the pair
while i < n and arr[i] == ele1:
i += 1
cnt1 += 1
# If both the elements are same, then count of
# pairs = the number of ways to choose 2
# elements among cnt1 elements
if ele1 == ele2:
cnt += (cnt1 * (cnt1 - 1)) // 2
# If the elements are different, then count of
# pairs = product of the count of both elements
else:
cnt += (cnt1 * cnt2)
return cnt
if __name__ == "__main__":
arr = [1, 4, 1, 4, 5]
k = 3
print(countPairs(arr, k))
C#
// C# Program to count all pairs with difference equal to k
// using Two Pointer Technique
using System;
using System.Linq;
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.Length;
int cnt = 0;
Array.Sort(arr);
int i = 0, j = 0;
while (j < n) {
// If the difference is greater than k, increase
// the difference by moving j pointer towards right
if (arr[j] - arr[i] < k)
j++;
// If difference is greater than k, decrease the
// difference by moving i pointer towards right
else if (arr[j] - arr[i] > k)
i++;
// If difference is equal to k, count all such pairs
else {
int ele1 = arr[i], ele2 = arr[j];
int cnt1 = 0, cnt2 = 0;
// Count frequency of first element of the pair
while (j < n && arr[j] == ele2) {
j++;
cnt2++;
}
// Count frequency of second element of the pair
while (i < n && arr[i] == ele1) {
i++;
cnt1++;
}
// If both the elements are same, then count of
// pairs = the number of ways to choose 2
// elements among cnt1 elements
if (ele1 == ele2)
cnt += (cnt1 * (cnt1 - 1)) / 2;
// If the elements are different, then count of
// pairs = product of the count of both elements
else
cnt += (cnt1 * cnt2);
}
}
return cnt;
}
static void Main(string[] args) {
int[] arr = { 1, 4, 1, 4, 5 };
int k = 3;
Console.WriteLine(countPairs(arr, k));
}
}
JavaScript
// JavaScript Program to count all pairs with difference
// equal to k using Two Pointer Technique
function countPairs(arr, k) {
const n = arr.length;
let cnt = 0;
arr.sort((a, b) => a - b);
let i = 0, j = 0;
while (j < n) {
// If the difference is greater than k, increase
// the difference by moving j pointer towards right
if (arr[j] - arr[i] < k)
j++;
// If difference is greater than k, decrease the
// difference by moving i pointer towards right
else if (arr[j] - arr[i] > k)
i++;
// If difference is equal to k, count all such pairs
else {
const ele1 = arr[i], ele2 = arr[j];
let cnt1 = 0, cnt2 = 0;
// Count frequency of first element of the pair
while (j < n && arr[j] === ele2) {
j++;
cnt2++;
}
// Count frequency of second element of the pair
while (i < n && arr[i] === ele1) {
i++;
cnt1++;
}
// If both the elements are same, then count of
// pairs = the number of ways to choose 2
// elements among cnt1 elements
if (ele1 === ele2)
cnt += (cnt1 * (cnt1 - 1)) / 2;
// If the elements are different, then count of
// pairs = product of the count of both elements
else
cnt += (cnt1 * cnt2);
}
}
return cnt;
}
const arr = [1, 4, 1, 4, 5];
const k = 3;
console.log(countPairs(arr, k));
[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:
- (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.
C++
// C++ Program to count all pairs with difference equal to k
// using Hash Map
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
int countPairs(vector<int> &arr, int k) {
int n = arr.size();
unordered_map<int, int> freq;
int cnt = 0;
for (int i = 0; i < n; i++) {
// Check if the complement (arr[i] + k)
// exists in the map. If yes, increment count
if (freq.find(arr[i] + k) != freq.end())
cnt += freq[arr[i] + k];
// Check if the complement (arr[i] - k)
// exists in the map. If yes, increment count
if (freq.find(arr[i] - k) != freq.end())
cnt += freq[arr[i] - k];
// Increment the frequency of arr[i]
freq[arr[i]]++;
}
return cnt;
}
int main() {
vector<int> arr = {1, 4, 1, 4, 5};
int k = 3;
cout << countPairs(arr, k);
return 0;
}
Java
// Java Program to count all pairs with difference equal to k
// using Hash Map
import java.util.HashMap;
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.length;
HashMap<Integer, Integer> freq = new HashMap<>();
int cnt = 0;
for (int i = 0; i < n; i++) {
// Check if the complement (arr[i] + k)
// exists in the map. If yes, increment count
if (freq.containsKey(arr[i] + k))
cnt += freq.get(arr[i] + k);
// Check if the complement (arr[i] - k)
// exists in the map. If yes, increment count
if (freq.containsKey(arr[i] - k))
cnt += freq.get(arr[i] - k);
// Increment the frequency of arr[i]
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
}
return cnt;
}
public static void main(String[] args) {
int[] arr = {1, 4, 1, 4, 5};
int k = 3;
System.out.println(countPairs(arr, k));
}
}
Python
# Python Program to count all pairs with difference equal to k
# using Hash Map
def countPairs(arr, k):
n = len(arr)
freq = {}
cnt = 0
for i in range(n):
# Check if the complement (arr[i] + k)
# exists in the map. If yes, increment count
if (arr[i] + k) in freq:
cnt += freq[arr[i] + k]
# Check if the complement (arr[i] - k)
# exists in the map. If yes, increment count
if (arr[i] - k) in freq:
cnt += freq[arr[i] - k]
# Increment the frequency of arr[i]
freq[arr[i]] = freq.get(arr[i], 0) + 1
return cnt
if __name__ == "__main__":
arr = [1, 4, 1, 4, 5]
k = 3
print(countPairs(arr, k))
C#
// C# Program to count all pairs with difference equal to k
// using Hash Map
using System;
using System.Collections.Generic;
class GfG {
static int countPairs(int[] arr, int k) {
int n = arr.Length;
Dictionary<int, int> freq = new Dictionary<int, int>();
int cnt = 0;
for (int i = 0; i < n; i++) {
// Check if the complement (arr[i] + k)
// exists in the map. If yes, increment count
if (freq.ContainsKey(arr[i] + k))
cnt += freq[arr[i] + k];
// Check if the complement (arr[i] - k)
// exists in the map. If yes, increment count
if (freq.ContainsKey(arr[i] - k))
cnt += freq[arr[i] - k];
// Increment the frequency of arr[i]
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
return cnt;
}
static void Main(string[] args) {
int[] arr = { 1, 4, 1, 4, 5 };
int k = 3;
Console.WriteLine(countPairs(arr, k));
}
}
JavaScript
// JavaScript Program to count all pairs with difference equal to k
// using Hash Map
function countPairs(arr, k) {
const n = arr.length;
const freq = {};
let cnt = 0;
for (let i = 0; i < n; i++) {
// Check if the complement (arr[i] + k)
// exists in the map. If yes, increment count
if ((arr[i] + k) in freq)
cnt += freq[arr[i] + k];
// Check if the complement (arr[i] - k)
// exists in the map. If yes, increment count
if ((arr[i] - k) in freq)
cnt += freq[arr[i] - k];
// Increment the frequency of arr[i]
freq[arr[i]] = (freq[arr[i]] || 0) + 1;
}
return cnt;
}
// Driver Code
const arr = [1, 4, 1, 4, 5];
const k = 3;
console.log(countPairs(arr, k));
Count pairs with absolute difference equal to k
Visit Course
Similar Reads
Count all distinct pairs with difference equal to K | Set 2 Given an integer array arr[] and a positive integer K, the task is to count all distinct pairs with differences equal to K. Examples: Input: arr[ ] = {1, 5, 3, 4, 2}, K = 3Output: 2Explanation: There are 2 distinct pairs with difference 3, the pairs are {1, 4} and {5, 2} Input: arr[] = {8, 12, 16, 4
6 min read
Count pairs from two arrays with difference exceeding K Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs(arr[i], brr[j]) such that (brr[j] - arr[i]) > K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] {10, 12, 7, 4, 2, 3}, K = 3 Output: 6 Explan
9 min read
Count pairs in an array whose absolute difference is divisible by K Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The p
14 min read
Count pairs in an array whose absolute difference is divisible by K Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The p
14 min read
Count pairs in an array whose absolute difference is divisible by K Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The p
14 min read
Count pairs in an array such that the absolute difference between them is ≥ K Given an array arr[] and an integer K, the task is to find the count of pairs (arr[i], arr[j]) from the array such that |arr[i] - arr[j]| ? K. Note that (arr[i], arr[j]) and arr[j], arr[i] will be counted only once.Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 3 All valid pairs are (1, 3), (1
6 min read