Tag Archives: unique pairs having difference

Find unique pairs with k difference (KDiff) (Hacker Rank Interview Question)

Input: Integer array
Diff: Integer difference

Output: Total number of unique pairs having difference provided in the input.

Here in this problem, the input will be an array of integer and also the difference value. So it will ask to out put either the total unique pairs of elements from the array having difference or just total count of that pairs.

So, with the use of hash set, it will be achieved in O(n) where n is the total number of elements in array.

Step to solve this question:
Step 1: Create a Set of all the elements.

Step 2: Iterate over each element in set

Check whether number (element value + diff) is in hashset.


Below is the java implementation and sample output.

You can have below code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git



import java.util.HashSet;
import java.util.Iterator;

public class KDiff {
	public static void main(String args[]){

		int pairCount = 0;
		Integer elements[] = {1,3,4,5,8,8};
		int kDiff = 2;
		if(elements.length>1 && kDiff>=1 && elements.length == elements.length){
			HashSet<Integer> hSet = new HashSet<Integer>();
			for(int i=0;i<elements.length;i++){
				int inputElement = elements[i];
			Iterator<Integer> itSet = hSet.iterator();
		    while (itSet.hasNext()) {
		    	Integer value = itSet.next();
		        Integer subtractValue =  value+kDiff;
		        	System.out.println("Pair Found:"+value+" & "+subtractValue);
	    System.out.println("Total Pairs:"+pairCount);		

Sample output of above code:

elements[] = {1,3,4,5,8,8};
int kDiff = 2;

Pair Found:1 & 3
Pair Found:3 & 5
Total Pairs:2

You can have above code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git