1. ARR = [5,3,7,1] and K=2
We can see for i=1 and j =2, ARR[i]-ARR[j] = 2 .
So we will return TRUE.
2. ARR = [-2,7,3,1,5] and K=10
We can see for any two indices it is not possible that the difference in their value is equal to K.
So we will return FALSE.
The first line of input contains a single integer 'T', representing the number of test cases.
Then the 'T' test cases follow.
The first line of each test case contains a number 'N' denoting the size of the array.
The second line contains 'N' space-separated distinct integers a1,βa2,β...,βaN β the array elements.
For each test case print βYESβ if there exists a pair of indices with difference 'K' else return βNOβ.
The output of every test case will be printed 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^5
-10^5 <= ARR[i] <= 10^5
Where 'T' denotes the number of test cases, 'N' denotes the number of elements in the array βARRβ respectively, and 'ARR[i]' denotes the 'i-th' element of the array 'ARR'.
Time limit: 1 second
The idea is to check the difference of all possible pairs or we can say for a given i we will check all possible values of j. More formally we can run two nested loops where outer loops will iterate over i and inner loop will iterate over j.
The idea is to first sort the array. Then letβs say if we are at index i then we need to search for value ARR[i]+K, and now we can do this task in log(N) using binary search as the array is already sorted.
We will scan the array from left to right and we will use the Hash to store all previously encountered elements. Whenever we encounter an element we will set its hash value to 1.
Now if we are at index i then we will find two value
Now we just need to find whether we previously encountered REQ1 or REQ2, if yes then we can return βYESβ.