K-diff Pairs in an Array - Problem

You're given an array of integers nums and an integer k. Your task is to find the number of unique k-diff pairs in the array.

A k-diff pair is defined as a pair of integers (nums[i], nums[j]) where:

  • 0 <= i, j < nums.length
  • i != j (different indices)
  • |nums[i] - nums[j]| == k (absolute difference equals k)

Important: We only count unique pairs - if the same pair of values appears multiple times in the array, it should only be counted once.

Example: In array [3, 1, 4, 1, 5] with k = 2, the pairs (1,3) and (3,5) both have an absolute difference of 2, so the answer is 2.

Input & Output

example_1.py โ€” Basic case with positive k
$ Input: nums = [3,1,4,1,5], k = 2
โ€บ Output: 2
๐Ÿ’ก Note: There are two 2-diff pairs: (1,3) and (3,5). Note that we count unique pairs, so even though 1 appears twice, we only count the pair (1,3) once.
example_2.py โ€” Case with duplicates and k=0
$ Input: nums = [1,2,3,4,5], k = 1
โ€บ Output: 4
๐Ÿ’ก Note: There are four 1-diff pairs: (1,2), (2,3), (3,4), and (4,5). Each consecutive pair has a difference of 1.
example_3.py โ€” Edge case with k=0
$ Input: nums = [1,3,1,5,4], k = 0
โ€บ Output: 1
๐Ÿ’ก Note: When k=0, we're looking for pairs with the same value. Only the number 1 appears more than once, so there's exactly 1 unique pair: (1,1).

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

One pass to build frequency map O(n) + one pass through unique elements O(n)

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash table to store frequency of all unique elements

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -107 โ‰ค nums[i] โ‰ค 107
  • 0 โ‰ค k โ‰ค 107
  • Follow-up: Can you solve this in O(n) time complexity?
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen