K-diff Pairs in an Array
K-diff Pairs in an Array is a medium arrays & hashing problem solved with the hashing pattern.
The best approach, optimal (hash map of counts), runs in O(n) time and O(n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (check every pair) up.
Problem
Given an integer array nums and an integer k, count the distinct pairs of values (a, b) that can be picked from two different positions of the array with |a - b| == k.
Two pairs are the same when they contain the same two values, no matter which positions they came from or in which order they are written: (2, 4) and (4, 2) are one pair. When k is 0, a pair like (5, 5) needs 5 to appear at least twice.
Return the number of distinct pairs.
Examples
Example 1
- Input
nums = [6, 2, 4, 2, 8], k = 2- Output
3- Why
- The pairs with a difference of 2 are (2, 4), (4, 6) and (6, 8). The value 2 appears twice, but (2, 4) is still only one distinct pair.
Example 2
- Input
nums = [1, 1, 1, 2, 2], k = 0- Output
2- Why
- With k = 0 a pair needs two equal values from different positions. Both 1 and 2 appear more than once, so (1, 1) and (2, 2) count. Three copies of 1 still give just one pair.
Example 3
- Input
nums = [1, 2, 3, 4, 5], k = 6- Output
0- Why
- The largest difference in the array is 5 - 1 = 4, so no pair is 6 apart.
Constraints
1 <= nums.length <= 10^4-10^7 <= nums[i] <= 10^70 <= k <= 10^7
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 22 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (check every pair) | O(n²) | O(n) |
| Sort and two pointers | O(n log n) | O(1) |
| Optimal (hash map of counts) | O(n) | O(n) |
1Brute force (check every pair)
O(n²)There are n * (n - 1) / 2 pairs of positions.O(n)The set can hold up to n distinct smaller values.Look at every pair of positions i < j. If the two values differ by exactly k, record the smaller of the two in a set. A pair (a, a + k) is completely determined by a, so the set removes repeats automatically, and its size is the answer.
- Create an empty set of smaller values.
- For every i < j: if |nums[i] - nums[j]| == k, add min(nums[i], nums[j]) to the set.
- Return the size of the set.
class Solution {
public int findPairs(int[] nums, int k) {
Set<Integer> smaller = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (Math.abs(nums[i] - nums[j]) == k) {
smaller.add(Math.min(nums[i], nums[j]));
}
}
}
return smaller.size();
}
}class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
smaller = set()
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if abs(nums[i] - nums[j]) == k:
smaller.add(min(nums[i], nums[j]))
return len(smaller)class Solution {
public:
int findPairs(vector<int>& nums, int k) {
unordered_set<int> smaller;
for (int i = 0; i < (int) nums.size(); i++) {
for (int j = i + 1; j < (int) nums.size(); j++) {
if (abs(nums[i] - nums[j]) == k) {
smaller.insert(min(nums[i], nums[j]));
}
}
}
return smaller.size();
}
};function findPairs(nums, k) {
const smaller = new Set();
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (Math.abs(nums[i] - nums[j]) === k) {
smaller.add(Math.min(nums[i], nums[j]));
}
}
}
return smaller.size;
}2Sort and two pointers
O(n log n)Sorting costs O(n log n); after that, i and j each move forward at most n times.O(1)Only the two pointers, apart from the sort itself.Sort the array. Keep a left pointer i and a right pointer j > i. If nums[j] - nums[i] is smaller than k, the gap must grow, so move j right. If it is larger, the gap must shrink, so move i right. When the gap is exactly k, that is one pair: count it, then move i past every copy of the same value, so the pair is never counted twice. Because the array is sorted, both pointers only move forward.
- Sort nums. Set i = 0, j = 1 and count = 0.
- While j < n: if j <= i or nums[j] - nums[i] < k, move j right.
- Else if nums[j] - nums[i] > k, move i right.
- Else count a pair, and move i right until it reaches a different value.
- Return count.
class Solution {
public int findPairs(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length, i = 0, j = 1, count = 0;
while (j < n) {
if (j <= i || nums[j] - nums[i] < k) {
j++;
} else if (nums[j] - nums[i] > k) {
i++;
} else {
count++;
int value = nums[i];
while (i < n && nums[i] == value) i++;
}
}
return count;
}
}class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
nums.sort()
n = len(nums)
i, j, count = 0, 1, 0
while j < n:
if j <= i or nums[j] - nums[i] < k:
j += 1
elif nums[j] - nums[i] > k:
i += 1
else:
count += 1
value = nums[i]
while i < n and nums[i] == value:
i += 1
return countclass Solution {
public:
int findPairs(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int n = nums.size(), i = 0, j = 1, count = 0;
while (j < n) {
if (j <= i || nums[j] - nums[i] < k) {
j++;
} else if (nums[j] - nums[i] > k) {
i++;
} else {
count++;
int value = nums[i];
while (i < n && nums[i] == value) i++;
}
}
return count;
}
};function findPairs(nums, k) {
nums.sort((a, b) => a - b);
const n = nums.length;
let i = 0, j = 1, count = 0;
while (j < n) {
if (j <= i || nums[j] - nums[i] < k) {
j++;
} else if (nums[j] - nums[i] > k) {
i++;
} else {
count++;
const value = nums[i];
while (i < n && nums[i] === value) i++;
}
}
return count;
}3Optimal (hash map of counts)
O(n)One pass builds the map and one pass over the distinct values does O(1) lookups.O(n)The map holds up to n distinct values.Count how many times each value appears. Then go over the distinct values once. For k > 0, a value a starts a pair exactly when a + k is also a key. For k = 0, a value starts a pair exactly when it appears at least twice. Each distinct value is the smaller end of at most one pair, so every pair is counted once.
- Build a map from each value to how many times it appears.
- For each distinct value a: if k == 0, count it when its frequency is at least 2.
- Otherwise count it when the map contains a + k.
- Return the count.
class Solution {
public int findPairs(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.merge(x, 1, Integer::sum);
int count = 0;
for (Map.Entry<Integer, Integer> e : freq.entrySet()) {
if (k == 0) {
if (e.getValue() >= 2) count++;
} else if (freq.containsKey(e.getKey() + k)) {
count++;
}
}
return count;
}
}class Solution:
def findPairs(self, nums: List[int], k: int) -> int:
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
count = 0
for a, c in freq.items():
if k == 0:
if c >= 2:
count += 1
elif a + k in freq:
count += 1
return countclass Solution {
public:
int findPairs(vector<int>& nums, int k) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
int count = 0;
for (auto& [a, c] : freq) {
if (k == 0) {
if (c >= 2) count++;
} else if (freq.count(a + k)) {
count++;
}
}
return count;
}
};function findPairs(nums, k) {
const freq = new Map();
for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
let count = 0;
for (const [a, c] of freq) {
if (k === 0) {
if (c >= 2) count++;
} else if (freq.has(a + k)) {
count++;
}
}
return count;
}Edge cases to test
- k = 0: a value counts once if it appears at least twice, and never if it appears once
- A single element: no pair is possible, so the answer is 0
- Many duplicates with k > 0: (a, a + k) is one pair no matter how many copies of a or a + k exist
- Negative values: (-3, -1) is a valid pair for k = 2
- k larger than the whole spread of the array: the answer is 0
- a + k can reach 2 * 10^7, which still fits in an int
Hints
Hint 1
A pair is fixed by its smaller value: if the smaller one is a, the other must be a + k. So count the distinct values a for which a + k is also present.
Hint 2
k = 0 is special: a + k is a itself, so you need a second copy of a, not just a itself.
Hint 3
After sorting, two pointers can find all pairs in one pass. A hash map of counts finds them without sorting.
FAQ
What is the best time complexity for K-diff Pairs in an Array?
Optimal (hash map of counts) runs in O(n) time and O(n) extra space. One pass builds the map and one pass over the distinct values does O(1) lookups.
Which pattern does K-diff Pairs in an Array use?
It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.
Is there a brute force solution for K-diff Pairs in an Array?
Yes. Brute force (check every pair) takes O(n²) time and O(n) space. Look at every pair of positions i < j.
Which edge cases should I test for K-diff Pairs in an Array?
k = 0: a value counts once if it appears at least twice, and never if it appears once; A single element: no pair is possible, so the answer is 0; Many duplicates with k 0: (a, a + k) is one pair no matter how many copies of a or a + k exist; Negative values: (-3, -1) is a valid pair for k = 2; k larger than the whole spread of the array: the answer is 0; a + k can reach 2 10^7, which still fits in an int.