Tag Archives: KDiff problem Hacker Rank

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

HackerRankProjectStructure

 

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];
				if(!hSet.contains(inputElement)){
					hSet.add(inputElement);
				}
			}
		
			Iterator<Integer> itSet = hSet.iterator();
			
		    while (itSet.hasNext()) {
		    	
		    	Integer value = itSet.next();
		        Integer subtractValue =  value+kDiff;
		        
		        if(hSet.contains(subtractValue)){
		        	System.out.println("Pair Found:"+value+" & "+subtractValue);
		        	pairCount++;
		        }
		    }
		}else{
			pairCount=0;
		}
		
	    System.out.println("Total Pairs:"+pairCount);		
	}
}

Sample output of above code:

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

Output:
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