K-diff Pairs in an Array

MediumArrays & Hashinghashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an integer array nums and a non-negative integer k, count the **unique** k-diff pairs in the array. A k-diff pair is a pair of values (x, y) taken from two different indices where |x - y| == k. Pairs are identified by their values, unordered: (1, 3) and (3, 1) are the same pair, and it counts once no matter how many index pairs produce it. When k == 0 a pair needs a value that occurs at least twice. Return the count in O(n) time.

Examples

Input: nums = [3,1,4,1,5], k = 2
Output: 2
The unique pairs are (1, 3) and (3, 5). The two 1s do not create a second (1, 3).
Input: nums = [1,2,3,4,5], k = 1
Output: 4
(1, 2), (2, 3), (3, 4), (4, 5).
Input: nums = [1,3,1,5,4], k = 0
Output: 1
Only the value 1 occurs twice, giving the pair (1, 1).

Constraints

  • 1 <= nums.length <= 10^4
  • -10^7 <= nums[i] <= 10^7
  • 0 <= k <= 10^7

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems