K-diff Pairs in an Array

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]) where 0 <= i, j < nums.length, i != j, and |nums[i] - nums[j]| == k. Pairs are unique by their values.

30:00

K-diff Pairs in an Array
medium
Free written solution
Topics
Companies

Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. A k-diff pair is an integer pair (nums[i], nums[j]) where 0 <= i, j < nums.length, i != j, and |nums[i] - nums[j]| == k. Pairs are unique by their values.

Example 1:
Input: {"nums":[3,1,4,1,5],"k":2}
Output: 2
Constraints:
  • 1≤nums.length≤1041 \leq \text{nums.length} \leq 10^4

  • −107≤nums[i]≤107-10^7 \leq \text{nums}[i] \leq 10^7

  • 0≤k≤1070 \leq k \leq 10^7

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,1,4,1,5],"k":2}

A 2-diff pair is a value x together with x + 2. First count every value so each lookup is O(1).

nums · k = 2

3
1
4
1
5

count map, in value order (0 distinct)

empty

unique pairs = 0

none yet

Variables
VariableValue
k2
distinct0
pairs0
DepthFunction Call
Stack empty
0/11