K-diff Pairs in an Array
Problem
Given an integer array nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is defined as an integer pair (nums[i], nums[j]) where i != j and |nums[i] - nums[j]| == k.
- 1 ≤ nums.length ≤ 10⁴
- −10⁷ ≤ nums[i] ≤ 10⁷
- 0 ≤ k ≤ 10⁷
Example
nums = [3, 1, 4, 1, 5], k = 22The unique pairs with difference 2 are (1, 3) and (3, 5). The algorithm first counts the frequency of each number: {1: 2, 3: 1, 4: 1, 5: 1}. Since k is 2, it checks for each number if number + 2 exists. For 1, 3 exists; for 3, 5 exists; for 4, 6 does not exist; for 5, 7 does not exist. Thus, two pairs are counted. If k were 0, the algorithm would count numbers with frequency greater than 1.
Approach
Straightforward Solution
A brute-force approach would check every pair of numbers, resulting in O(n^2) time complexity, which is inefficient for large inputs.
Core Observation
The problem reduces to counting unique pairs where the difference between elements is exactly k. This can be reframed as checking for each number if its complement (number + k) exists, or if k is zero, counting duplicates.
Path to Optimal
Recognizing that the problem is about existence and frequency of numbers, a hash map (dictionary) can store counts of each number. For k > 0, iterating over keys and checking if key + k exists allows counting pairs in O(n) time. For k = 0, pairs correspond to numbers appearing more than once. This approach avoids nested loops and leverages O(1) average lookup time.
Optimal Approach
Build a frequency map of all numbers. If k == 0, count how many numbers appear more than once. Otherwise, for each unique number, check if number + k exists in the map and increment the pair count accordingly. This yields an O(n) time and space solution.
Time
O(n)
Building the frequency map takes O(n). Iterating over the keys and checking for complements is O(n) on average due to O(1) hash map lookups.
Space
O(n)
The frequency map stores counts for up to n unique numbers, requiring O(n) auxiliary space.
Pattern Spotlight
Hash Maps (Frequency Counting and Complement Lookup)
When counting pairs with a fixed difference, transform the problem into a frequency map and check for complements in O(1) time, enabling a single pass solution that avoids costly nested loops.
Solution
| 1 | class Solution: |
| 2 | def findPairs(self, nums: list[int], k: int) -> int: |
| 3 | counts = {} |
| 4 | |
| 5 | for num in nums: |
| 6 | counts[num] = counts.get(num, 0) + 1 |
| 7 | |
| 8 | pairs = 0 |
| 9 | |
| 10 | for num in counts: |
| 11 | if k == 0: |
| 12 | if counts[num] > 1: |
| 13 | pairs += 1 |
| 14 | else: |
| 15 | if num + k in counts: |
| 16 | pairs += 1 |
| 17 | |
| 18 | return pairs |
Step-by-Step Solution
Build Frequency Map of Numbers
| 3 | counts = {} |
| 5 | for num in nums: |
| 6 | counts[num] = counts.get(num, 0) + 1 |
Objective
To count the occurrences of each number in the input array for efficient lookup.
Key Insight
By storing the frequency of each number in a hash map, the algorithm can quickly determine if a complement exists or if duplicates are present. This transforms the problem from pairwise comparison to simple membership and frequency checks, enabling O(n) time complexity.
Interview Quick-Check
Core Logic
The frequency map enables O(1) average-time lookups to check for complements or duplicates.
Common Pitfalls & Bugs
Forgetting to increment counts correctly or initializing counts improperly can lead to incorrect pair counts.
Count Unique k-diff Pairs Using Frequency Map
| 8 | pairs = 0 |
| 10 | for num in counts: |
| 11 | if k == 0: |
| 12 | if counts[num] > 1: |
| 13 | pairs += 1 |
| 14 | else: |
| 15 | if num + k in counts: |
| 16 | pairs += 1 |
Objective
To iterate over unique numbers and count valid pairs based on the value of k.
Key Insight
The algorithm distinguishes two cases: when k is zero, pairs are duplicates (frequency > 1); when k is positive, pairs exist if the complement (number + k) is present. This conditional logic ensures correctness and efficiency by leveraging the frequency map for constant-time membership checks.
Interview Quick-Check
Core Logic
For k=0, count numbers with frequency > 1; for k>0, count numbers whose complement (num + k) exists in the map.
State & Boundaries
Iterate over unique keys only, ensuring each pair is counted once and avoiding duplicates.
Common Pitfalls & Bugs
Failing to handle k=0 separately can cause incorrect counts, as pairs require duplicates rather than distinct complements.
Return the Total Count of Unique k-diff Pairs
| 18 | return pairs |
Objective
To output the final count of unique pairs found.
Key Insight
Returning the accumulated count completes the solution, reflecting the total number of unique pairs that satisfy the k-diff condition. This step finalizes the algorithm's result after all checks.
Interview Quick-Check
Core Logic
Return the accumulated count after processing all unique numbers.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
counts[num] = counts.get(num, 0) + 1
Increment the count for the current number in the frequency map.
Accurately tracking the frequency of each number is critical to distinguish duplicates (for k=0) and to verify the existence of complements (for k>0).
if num + k in counts:
Check if the complement (num + k) exists in the frequency map.
This membership check identifies valid pairs efficiently, leveraging the hash map's O(1) average lookup time.
counts = {}
Initialize an empty dictionary to store counts of each number.
This dictionary will serve as a frequency map, enabling constant-time lookups for complements and duplicates, which is essential for efficient pair counting.
if counts[num] > 1:
Check if the current number appears more than once.
Only numbers with frequency greater than one can form valid pairs when k=0, ensuring correctness in counting duplicates.
pairs += 1
Increment the pair count when a valid complement is found.
Counting pairs only when the complement exists ensures accurate tallying of unique k-diff pairs without duplicates.
if k == 0:
Check if k equals zero to handle duplicate pairs.
The problem requires special handling when k=0 because pairs are formed by identical numbers appearing more than once, differing from the complement check for k>0.
pairs += 1
Increment the pair count for duplicates when k=0.
Counting duplicates as pairs when k=0 aligns with the problem's definition and prevents missing valid pairs.
return pairs
Return the total count of unique k-diff pairs found.
Returning the accumulated count completes the algorithm, providing the final answer as required by the problem.
for num in counts:
Iterate over each unique number in the frequency map.
Examining unique numbers ensures each potential pair is considered exactly once, preventing double counting.
else:
Handle the case when k is greater than zero.
For k>0, pairs are formed by distinct numbers differing by k, requiring a complement existence check.
for num in nums:
Iterate over each number in the input array.
Processing each number allows building the frequency map by counting occurrences, which is the foundation for the optimized solution.
pairs = 0
Initialize the counter for unique k-diff pairs.
This accumulator will track the total number of valid pairs found during iteration over the frequency map.
Test Your Understanding
Why does the algorithm treat the case k = 0 differently from k > 0?
Because when k = 0, pairs are formed by identical numbers appearing at least twice, so counting duplicates suffices. For k > 0, pairs are formed by distinct numbers differing by k, requiring complement checks.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct K-diff Pairs in an Array from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the K-diff Pairs in an Array drill