The K-diff Pairs in an Array interview question asks you to find the number of unique pairs such that their absolute difference is exactly k. For example, in [3, 1, 4, 1, 5] with , the pairs are and . Note that the question asks for unique pairs, so should only be counted once even if there are multiple 1s and 3s.
Companies like Apple and Microsoft ask this to evaluate a candidate's mastery of Hash Table interview patterns. It evaluates if you can handle edge cases like (finding duplicates) and if you can avoid comparisons by using a frequency map. It’s a test of efficient search and deduplication.
This problem is solved using a Frequency Map.
Array: [1, 1, 1, 2, 2], .
{1: 3, 2: 2}.[1, 3, 5], .Whenever you need to find pairs with a specific difference, always think about the "Complement" rule: X - Y = K means X = Y + K. This transforms a search for a pair into a search for a single value in a map. This is a vital Hash Table interview pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Check If N and Its Double Exist | Easy | Solve | |
| Intersection of Two Arrays II | Easy | Solve | |
| Intersection of Two Arrays | Easy | Solve | |
| Count the Number of Fair Pairs | Medium | Solve | |
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve |