Problem Statement
Given an array of positive integers arr[] and an integer k, count the total number of pairs whose absolute difference is strictly less than k.
Note
(i, j)and(j, i)are considered the same pair.Count each pair only once.
Example 1
Input
arr = [1, 10, 4, 2]
k = 3
Output
2
Explanation
Possible pairs:
| Pair | Difference | Valid? |
|---|---|---|
| (1, 10) | 9 | NO |
| (1, 4) | 3 | NO (must be less than 3) |
| (1, 2) | 1 | YES |
| (10, 4) | 6 | NO |
| (10, 2) | 8 | NO |
| (4, 2) | 2 | YES |
Total valid pairs = 2
Example 2
Input
arr = [2, 3, 4]
k = 5
Output
3
Explanation
Valid pairs:
(2, 3)(2, 4)(3, 4)
Answer = 3
Brute Force Approach
The simplest approach is to check every pair.
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (Math.abs(arr[i] - arr[j]) < k) {
count++;
}
}
}
Time Complexity
O(n²)
If:
n = 100000
this approach becomes extremely slow.
Therefore, we need a better solution.
Optimized Approach
We use:
Sorting
Two Pointers (Sliding Window)
Why Sorting?
Suppose the array is:
1 10 4 2
After sorting:
1 2 4 10
Now the numbers are arranged in increasing order.
This gives an important property:
arr[right] - arr[left]
is always the absolute difference because:
arr[right] >= arr[left]
So we no longer need Math.abs().
Idea Behind Two Pointers
Suppose the sorted array is:
1 2 4 10
Initially:
L
R
1 2 4 10
Difference:
2 - 1 = 1
1 < 3
This pair is valid.
Since the array is sorted, there are:
right - left
1 - 0 = 1
new valid pair.
Move the right pointer.
Now:
L
R
1 2 4 10
Difference:
4 - 1 = 3
Not less than 3.
Move the left pointer.
L
R
1 2 4 10
Difference:
4 - 2 = 2
Valid.
Now:
right - left
2 - 1 = 1
One more pair.
Move the right pointer.
Now:
L
R
1 2 4 10
Difference:
10 - 2 = 8
Too large.
Move the left pointer repeatedly until the difference becomes smaller.
Eventually, the loop ends.
Total valid pairs = 2.
Visualization
Sorted Array
1 2 4 10
L
R
Valid
↓
L
R
Invalid
↓
L
R
Valid
↓
L
R
Invalid
↓
End
Complete Code
import java.util.Arrays;
class Solution {
public static int countPairs(int arr[], int k) {
Arrays.sort(arr);
int n = arr.length;
int left = 0;
int right = 1;
int count = 0;
while (right < n) {
if (arr[right] - arr[left] < k) {
count += (right - left);
right++;
}
else {
left++;
if (left == right)
right++;
}
}
return count;
}
}

Join the conversation! Your thoughts help the community grow.