Skip to content

Instantly share code, notes, and snippets.

@longda
Created April 7, 2017 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save longda/5c063a734e024eb4358e44bb80f38a5d to your computer and use it in GitHub Desktop.
Save longda/5c063a734e024eb4358e44bb80f38a5d to your computer and use it in GitHub Desktop.
Hacker Rank Challenge - Pairs - https://www.hackerrank.com/challenges/pairs
/*
https://www.hackerrank.com/challenges/pairs
Given N integers, count the number of pairs of integers whose difference is K.
Input Format
The first line contains N and K.
The second line contains N numbers of the set. All the N numbers are unique.
Constraints
2 <= N <= 10^5
0 < K < 10^9
Each integer will be greater than 0 and at least K smaller than 2^31 - 1.
Output Format
An integer that tells the number of pairs of integers whose difference is K.
Sample Input
5 2
1 5 3 4 2
Sample Output
3
Explanation
There are 3 pairs of integers in the set with a difference of 2.
*/
static int pairs(int[] a, int k)
{
var target = k;
var count = 0;
var diff = 0;
var i = 0;
var j = 0;
System.Array.Sort(a);
for (i = 0; i < a.Length - 1; i++)
{
for (j = i + 1; j < a.Length; j++)
{
diff = a[j] - a[i];
if (diff == target)
{
count++;
}
else if (diff > target)
{
break;
}
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment