Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Last Updated: 11 Jan, 2021

Pair Difference K

Asked in companies
BarclaysFacebookTata Consultancy Services (TCS)

Problem statement

You are given a sorted array ARR of integers of size N and an integer K. You have to find whether it is possible to find a pair of integers having an absolute difference of K.


1. K is a non-negative integer.

2. Absolute Difference between two integers A and B is equal to the difference of maximumOf(A, B) and minimumOf(A, B).

3. Pair of integers should have different indices in the array.
Input format:
The first line of input contains an integer T, denoting the number of test cases.

The first line of each test case consists of two space-separated integers N and K, denoting the size of the given array ARR and the required absolute difference.

The second line of each test case consists of N space-separated integers denoting the elements of the array.
Output format:
For each test case print, “Yes” if it is possible to have a pair of integers having absolute difference equal to K and “No” otherwise, in a separate line.
You don't have to print anything, it has already been taken care of. Just Implement the given function.
1 <= T <= 100
1 <= N <= 10^4
1 <= ARR[i] <= 10^9
0 <= K <= 10^9

Time Limit: 1 sec.


01 Approach

  • Iterate through the array ARR (with for loop variable i), consider this as one of the possible element in pair and let’s call it A(A = ARR[i]).
  • For each element A, iterate through the array ARR(with for loop variable j), consider this as the possible other element in the pair along with A. And let’s call it B(B = ARR[j]). But if i is equal to j then you cannot make this pair, hence move forward and try other pairs.
  • If the absolute difference between A and B (|A-B|), is equal to K, then we get the required pair and we can print “Yes”.
  • If after trying all possible pairs in the array we are unable to find the required pair we simply print “No”.