333. K-diff Pairs in an Array

Medium
Unique Difference Pair Counting
Hashing

Problem

Given an integer array nums and a non-negative integer k, return the number of unique pairs of values whose absolute difference is exactly k. Pairs with the same two values count only once.

Examples

Example 1

Input: [3,1,4,1,5], 2
Output: 2

Example 2

Input: [1,2,3,4,5], 1
Output: 4

Example 3

Input: [1,3,1,5,4], 0
Output: 1
Constraints

1 <= nums.length <= 10000

-10000000 <= nums[i] <= 10000000

0 <= k <= 10000000

Hints

?? For k greater than zero, distinct values x and x + k form one pair.

?? For k equal to zero, only values appearing at least twice form pairs.

?? A frequency map handles both cases naturally.

Expected Complexity
Time: O(n)
Space: O(n)
Follow-up

How does the k = 0 case differ from the k > 0 case?

Practice Notes

Attempts: 0

Time spent: 0min

Hints used: 0

00:00
Loading...
Case 1
Case 2
Case 3
Input
[3,1,4,1,5], 2
Expected
2