How do you count pairs with absolute difference K in O(n) time while handling duplicate values accurately?
Counting Pairs with Absolute Difference $K$ in $O(n)$ Time (With Duplicates)
To count pairs $(i, j)$ with $i < j$ (or unordered value pairs, depending on problem convention) such that $\vert{}a - b\vert{} = K$ in $O(n)$ time:
- Hash Map Frequency Count: Count how often each value appears in a hash map (
freq), then iterate over each distinct valuexinfreq. - Case $K > 0$: For each
x, look upx + Kinfreq(looking up onlyx + Kavoids double-counting the same pair viax - K). Addfreq[x] * freq[x + K]to the answer. - Case $K = 0$: Pairs with $\vert{}x - x\vert{} = 0$ are identical elements. For each
xwith frequency $c$, the number of distinct index pairs $(i, j)$ with $i < j$ is $\binom{c}{2} = \frac{c \cdot (c - 1)}{2}$. - Case $K < 0$: Absolute difference $\vert{}a - b\vert{}$ is always non-negative, so no valid pair exists when $K < 0$ (return
0).
Why x + K Only (When $K > 0$) Prevents Double Counting
Suppose nums = [1, 5, 3, 1] and $K = 2$. Frequency map: {1: 2, 3: 1, 5: 1}.
If you checked both x + K and x - K for every x in freq:
- At
x = 1:1 + 2 = 3gives2 * 1 = 2pairs ((index 0, 3)? No,1and3: indices0with2, and3with2). - At
x = 3:3 - 2 = 1would count those exact same pairs again.
Checking only x + K for each unique key x in freq visits every unordered value pair {x, x + K} once, multiplying their counts (freq[x] * freq[x + K]) to get all index combinations.
(Note: If a problem asks for distinct value pairs (min(x, y), max(x, y)) rather than index pairs, add 1 instead of freq[x] * freq[x + K] when x + K in freq for $K > 0$, and add 1 when freq[x] >= 2 for $K = 0$.)
Code Implementation
Python Solution (Index Pairs)
from collections import Counter
def count_pairs_with_abs_diff_k(nums: list[int], k: int) -> int:
if k < 0:
return 0
freq = Counter(nums)
total_pairs = 0
if k == 0:
for count in freq.values():
if count >= 2:
total_pairs += count * (count - 1) // 2
return total_pairs
for x, count in freq.items():
target = x + k
if target in freq:
total_pairs += count * freq[target]
return total_pairs
C++ Solution (Index Pairs)
#include <vector>
#include <unordered_map>
#include <cstdint>
long long countPairsWithAbsDiffK(const std::vector<int>& nums, int k) {
if (k < 0) {
return 0;
}
std::unordered_map<long long, long long> freq;
freq.reserve(nums.size());
for (int x : nums) {
freq[static_cast<long long>(x)]++;
}
long long total_pairs = 0;
long long lk = static_cast<long long>(k);
if (lk == 0) {
for (const auto& [_, count] : freq) {
if (count >= 2) {
total_pairs += (count * (count - 1)) / 2;
}
}
return total_pairs;
}
for (const auto& [x, count] : freq) {
auto it = freq.find(x + lk);
if (it != freq.end()) {
total_pairs += count * it->second;
}
}
return total_pairs;
}
Complexity
- Time Complexity: $O(n)$ average — building the frequency map takes $O(n)$ and iterating over at most $n$ unique keys takes $O(n)$ with $O(1)$ average hash lookups.
- Auxiliary Space: $O(n)$ — stores up to $n$ unique elements and their counts in the hash map.
You must log in or register to comment.
