Last active
December 5, 2024 10:59
Given an array of distinct integer values, count the number of pairs of integers that have difference k.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given an array of distinct integer values, count the number of pairs of integers that | |
// have difference k. For example, given the array [1, 7, 5, 9, 2, 12, 3] and the difference | |
// k = 2, there are four pairs with difference 2: (1, 3), (3, 5), (5, 7), (7, 9). | |
CountPairsWithDifference([1, 7, 5, 9, 2, 12, 3], 2).Dump(); // 4 | |
CountPairsWithDifference([int.MaxValue, int.MinValue, int.MaxValue - 2, int.MinValue + 2], 2).Dump(); // 2 | |
CountPairsWithDifference([1, 7, 5, 9, 2, 12, 3], 0).Dump(); // 0 | |
CountPairsWithDifference([1, 7, 5, 9, 2, 12, 3], -2).Dump(); // 4 | |
int CountPairsWithDifference(int[] integers, int diff) | |
{ | |
if (diff is 0) | |
return 0; | |
diff = Math.Abs(diff); | |
var set = new HashSet<int>(integers); | |
var numOfPairs = 0; | |
foreach (var i in integers) | |
if (i <= int.MaxValue - diff && set.Contains(i + diff)) | |
numOfPairs++; | |
return numOfPairs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment