in Algorithms
12,484 views
4 votes
4 votes

Q) Consider a sorted array of n numbers. What would be the time complexity of the best known algorithm to find a pair a and b such that |a-b| = k , k being a positive integer.

a) O(logn)

b) O(n)

c)O(nlogn)

d)O(n^2)

Which of the option is Correct And Why?

in Algorithms
12.5k views

2 Comments

i believe answer is O(nlogn) . Question is taken from geekforgeeks mock test but progrma for it not given ,

I found this https://www.geeksforgeeks.org/count-pairs-difference-equal-k/ here time is not less than O(nlogn).

anyone write its code  for O(n) :)

1
1
what will be the solution if it ask to find more than one pairs whose difference is k???
0
0

7 Answers

0 votes
0 votes
Sorting do not affect the time complexity of the problem. It remain O(nlogn).

Steps for this problem:

1- Trace each element(say x) in series with the help of loop.   //O(n)

     a) Calculate b1=a-k and b2=a+k; //since |a-b|=k can be written as a-b=k or b-a=k.  //O(1)

     b) Now using binary search find whether b1 or b2 present in the remaining array other than the selected element(x).                                                                                                                                                  // O(logn)+O(logn)

     c) if yes then print else carry on for the next iteration.

Overall time complexity will be O(nlogn).
0 votes
0 votes
fxn(){

Take two pointer i=0 and j=n-1

while(i<j){

      if( abs(a-b) == k){

         print a and b

     }else if(abs(a-b) < k)

         i++;

else j---;

}

print "no such combination exist";

}

It will take O(n)
0 votes
0 votes
It doesn't matter whether the array is sorted or not, we can do it in O(n) (linear time) time. Use hashing.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n,k;
    cin>>n>>k;
    int arr[n];
    map<int,int>mp;      // for hashing ()
    for(int i=0;i<n;i++)
    cin >>arr[i];
    
    for(int i=0;i<n;i++)  // O(n)
    {
        if(mp[arr[i]-k] || mp[arr[i]+k])
        {
            cout<<"Present"<<endl;
            break;
        }
        mp[arr[i]]=1;
    }
    return 0;
}
Answer: