K-diff Pairs in an Array - Problem

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 the following are true:

  • 0 <= i, j < nums.length
  • i != j
  • |nums[i] - nums[j]| == k

Notice that |val| denotes the absolute value of val.

Input & Output

Example 1 — Basic Case
$ 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 only count unique pairs, so (1,3) from different positions counts as one pair.
Example 2 — No Valid Pairs
$ Input: nums = [1,2,3,4,5], k = 1
Output: 4
💡 Note: Valid pairs are (1,2), (2,3), (3,4), and (4,5). Each consecutive pair has difference 1.
Example 3 — Duplicate Elements
$ Input: nums = [1,3,1,5,4], k = 0
Output: 1
💡 Note: For k=0, we need identical pairs. Only the number 1 appears more than once, giving us one unique pair (1,1).

Constraints

  • 1 ≤ nums.length ≤ 104
  • -107 ≤ nums[i] ≤ 107
  • 0 ≤ k ≤ 107

Visualization

Tap to expand
K-diff Pairs in an Array INPUT nums array: 3 i=0 1 i=1 4 i=2 1 i=3 5 i=4 k = 2 K-diff pair: |nums[i] - nums[j]| == k where i != j nums=[3,1,4,1,5], k=2 ALGORITHM STEPS 1 Build Hash Map Count frequency of each num 1 --> 2 3 --> 1 4 --> 1 5 --> 1 2 For each unique num Check if (num + k) exists 3 Find pairs with k=2 1+2=3 exists? YES 3+2=5 exists? YES 4+2=6 exists? NO 5+2=7 exists? NO 4 Count unique pairs O(n) time complexity O(n) lookup FINAL RESULT Valid K-diff Pairs Found: Pair 1: (1, 3) |1 - 3| = 2 = k OK - Valid! Pair 2: (3, 5) |3 - 5| = 2 = k OK - Valid! OUTPUT 2 2 unique k-diff pairs with difference k=2 Key Insight: Using a Hash Map gives O(1) lookup time. For each unique number n, we check if (n + k) exists in the map. This avoids O(n^2) brute force. Special case: when k=0, we count numbers that appear more than once. Using unique keys ensures we count each pair only once, avoiding duplicates like (1,3) and (3,1). TutorialsPoint - K-diff Pairs in an Array | Hash Map - O(n) Lookup
Asked in
Amazon 25 Google 18 Microsoft 12 Facebook 8
67.0K Views
Medium Frequency
~25 min Avg. Time
2.2K 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