//Given an array arr[N],, check if any pair (i,j) exist such that arr[i] + arr[j]==K , and i!=j;Count these kind of pair
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static int countPairSum(int [] arr , int k ){
int count = 0 ;
HashMap<Integer,Integer> fmap = new HashMap<>();
for(int i=0; i < arr.length ; i++){
int fval = arr[i];
int sval = k - arr[i];
//Check the frq of sval in past
if(fmap.containsKey(sval) ){
count+= fmap.get(sval);
}
//increase the freq of current element
if(fmap.containsKey(fval)){
int oldFreq = fmap.get(fval);
fmap.put(fval,oldFreq+1);
}
else{
fmap.put(fval,1);
}
}
return count;
}
public static void main(String[] args) {
int arr[] = {2, 5 , 2 , 5 , 8 , 5 , 2 , 8 };
int k = 10;
System.out.println("Final Count " + countPairSum(arr,k));
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: