Skip to content

Instantly share code, notes, and snippets.

@vjames19
Last active December 14, 2015 10:59
Show Gist options
  • Save vjames19/5076267 to your computer and use it in GitHub Desktop.
Save vjames19/5076267 to your computer and use it in GitHub Desktop.
Pairs HackerrankGiven N numbers [N<=10^5], count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]Input Format:1st line contains N & K (integers).2nd line contains N numbers of the set. All the N numbers are assured to be distinct.Output Format:One integer saying the no of pairs of numbers that have a diff K.Sample Input #0…
package search.pairs;
/* Head ends here */
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
set.add(in.nextInt());
}
findPairs(set, k);
}
private static void findPairs(Set<Integer> set, int k) {
int pairs = 0;
for(Integer i: set){
pairs += set.contains(i+k) ? 1:0;
}
System.out.println(pairs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment