(Hacker Rank) Pairs - Solution
Link to the problem: https://www.hackerrank.com/challenges/pairs
The solution below sorts the given array. Then, for every element in the array, we apply the following steps:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int[] elements;
static boolean binSearch(int lo, int hi, int value) {
if (lo > hi) {
return false;
}
int m = (lo+hi)/2;
if (elements[m] < value) {
return binSearch(m+1, hi, value);
}
if (elements[m] > value) {
return binSearch(lo, m-1, value);
}
else {
return true;
}
}
static int pairs(int k) {
int count = 0;
for (int i = 0; i < elements.length; i++) {
int diff = elements[i]+k;
if (binSearch(i+1, elements.length-1, diff)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] s = line.split(" ");
int numElements = Integer.parseInt(s[0]);
int value = Integer.parseInt(s[1]);
elements = new int[numElements];
line = sc.nextLine();
s = line.split(" ");
for(int i = 0; i < numElements; i++) {
elements[i] = Integer.parseInt(s[i]);
}
Arrays.sort(elements);
System.out.println(pairs(value));
}
}
The solution below sorts the given array. Then, for every element in the array, we apply the following steps:
- Sum the element and the value of K;
- Call the Binary Search method to find out if the array contains the result of the sum;
- If the array contains the result of the sum, then we found a pair.
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int[] elements;
static boolean binSearch(int lo, int hi, int value) {
if (lo > hi) {
return false;
}
int m = (lo+hi)/2;
if (elements[m] < value) {
return binSearch(m+1, hi, value);
}
if (elements[m] > value) {
return binSearch(lo, m-1, value);
}
else {
return true;
}
}
static int pairs(int k) {
int count = 0;
for (int i = 0; i < elements.length; i++) {
int diff = elements[i]+k;
if (binSearch(i+1, elements.length-1, diff)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] s = line.split(" ");
int numElements = Integer.parseInt(s[0]);
int value = Integer.parseInt(s[1]);
elements = new int[numElements];
line = sc.nextLine();
s = line.split(" ");
for(int i = 0; i < numElements; i++) {
elements[i] = Integer.parseInt(s[i]);
}
Arrays.sort(elements);
System.out.println(pairs(value));
}
}
Comments
Post a Comment