Count Number of Pairs With Absolute Difference K (LeetCode 2006): Solution and Explanation

Easy
Array
Hash Table
Counting

Given an integer array nums and an integer k, count the index pairs (i, j) with i < j whose values differ by exactly k in absolute value.

Intuition

Checking every pair works for 200 elements, but it misses the structure of the condition. For a fixed value x, the only partners are values that sit exactly k below or k above it on the number line.

Count each pair at its later element. When the scan reaches x, the pairs that end here are the earlier copies of x - k plus the earlier copies of x + k. Both numbers come straight out of a count map of everything seen so far.

So the whole job is two lookups and one increment per element. Because k is at least 1, neither lookup can ever find x itself, which keeps the count honest.

Approach: One pass with a count per value

  1. Create an empty map count and set pairs = 0.
  2. For each value x, add count[x - k] + count[x + k] to pairs. Missing keys count as 0.
  3. Then increment count[x] so later elements can pair with this one.
  4. Return pairs after the loop.

Step-by-step example

nums = [1,2,2,1], k = 1
  1. x = 1 at index 0. count[0] and count[2] are both 0, so pairs stays 0. count[1] becomes 1.
  2. x = 2 at index 1. count[1] is 1 and count[3] is 0, so one pair is found and pairs = 1. count[2] becomes 1.
  3. x = 2 at index 2. count[1] is still 1, so pairs = 2. count[2] becomes 2.
  4. x = 1 at index 3. count[0] is 0 and count[2] is 2, so two more pairs are found and pairs = 4.
  5. The scan ends and the answer is 4.

Code: Python, Java, C++

1class Solution:
2    def countKDifference(self, nums: List[int], k: int) -> int:
3        count = {}
4        pairs = 0
5        for x in nums:
6            pairs += count.get(x - k, 0) + count.get(x + k, 0)
7            count[x] = count.get(x, 0) + 1
8        return pairs
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each element costs two map lookups and one update, all constant time.

Space

O(m)

The map stores one counter per distinct value. Since values are at most 100, a fixed array of about 200 slots also works.

Other approaches

Check every pair (time O(n^2), space O(1))

Two nested loops compare every i < j and count the pairs with the right difference. It is short and fast enough for n = 200.

Count first, then multiply (time O(n + m), space O(m))

Build the full frequency table, then for each value v add freq[v] * freq[v + k]. Looking only upward counts each unordered pair of values once.

Sort and two pointers (time O(n log n), space O(1) extra)

Sort the array and slide two pointers to find runs whose difference is k, multiplying run lengths. Sorting adds a log factor without any benefit here.

Common mistakes

  • Looking up only x - k. Pairs where the earlier element is larger need the x + k lookup too.
  • Incrementing count[x] before the lookups. With k >= 1 that does not create a self pair, but it is a habit that breaks the k = 0 variants of this problem.
  • In the count-then-multiply version, adding both freq[v] * freq[v + k] and freq[v] * freq[v - k], which counts every pair twice.
  • Indexing a fixed array with x - k when it can be zero or negative. Guard the index or use a map.

Frequently asked questions

Why is each pair counted exactly once?

A pair is added only when its later element is processed, and at that moment the earlier element is already in the count map. The earlier element never looks ahead, so it does not add the pair a second time.

Does the answer fit in a 32-bit integer?

Yes. With 200 elements there are at most 19,900 pairs in total.

How is this different from K-diff Pairs in an Array?

K-diff Pairs counts distinct value pairs, so duplicates collapse into one. Here every index pair counts separately, which is why a running count per value is the right tool.