Skip to content

Instantly share code, notes, and snippets.

@aannenko
Last active December 5, 2024 10:59
Show Gist options
  • Save aannenko/4d2c7773fb3e6c4df9b49fbf7fb961c3 to your computer and use it in GitHub Desktop.
Save aannenko/4d2c7773fb3e6c4df9b49fbf7fb961c3 to your computer and use it in GitHub Desktop.
Given an array of distinct integer values, count the number of pairs of integers that have difference k.
// 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