10. Find a pair with given differences
10. Find a pair with given differences
Problem link :- click here
package program;
import java.util.Arrays;
public class Searching__10
{
/*
Given an array arr[] of size n and a number diff, you need to write a
program to find if there exists a pair of elements in the array whose difference
is diff
arr[] = {5, 20, 3, 2, 5, 80} diff = 78
output : 1 or true
Lets sort the array first
and then take two pointers one at each end of the array
and check if the difference is found
*/
static Boolean findPair(int arr[], int n, int diff)
{
//sorting the array
Arrays.sort(arr);
int i, j;
i = 0;
j = 1;
while(j<n)
{
int diff1 = Math.abs(arr[i] - arr[j]);
if(diff1 == diff)
return true;
else if(diff < diff1)
i++;
else
j++;
}
return false;
}
public static void main(String[] args)
{
int arr[] = {5, 20, 3, 2, 5, 80};
int diff = 78;
Boolean ans = findPair(arr, arr.length, diff);
if(ans)
System.out.println("Found");
else
System.out.println("Not found");
}
}
Time complexity :- O(log(n))
Space complexity :- O(1)
Comments
Post a Comment