edited by
935 views
0 votes
0 votes

Given an array of n elements, what is the worst case time complexity to find minimum difference between any pair in given array?( 

  1.   O(log n)
  2.   O(nlogn)
  3.   O(n)
  4.   O(n2)
     
edited by

2 Answers

Best answer
2 votes
2 votes
Anser will be O(nlogn),   for any number it will give minimum differnece either with the number  which is just higher to it or just lower to  it and and have no benefit to check any number with all other number ( waste of iteration ).  

And if you sort the array , then it will fulfill our requirements,   for any ith number the number which is just greater then equals to it will be present on (i + 1 )th position and one which is just lower and equals to it is at position ( i - 1 ).

Pseudo code :

sort(arr , arr + n )             // 0 indexing based array

int res = infinite  ;

for(int i = 1 ; i < n ; ++i )  res = min( res ,  arr[i] - arr[i - 1] )

return res;    

Complexity  :  (nlogn + n )  = o(nlogn)  

As sorting also can be done in linear time with hashing( counting sort )  but they are asking for worst case , then we can assume sorting complexity to nlogn.

Hence  option 2 is correct : O(nlogn)
selected by
1 votes
1 votes
N logN is easy to find.

But not sure whether can be made better than that.

Related questions

2 votes
2 votes
1 answer
2
yes asked Oct 6, 2015
1,384 views
for example array contain a[1 2 3 3 3 3 3 4 5] then retun(1)
1 votes
1 votes
1 answer
3
radha gogia asked Jul 31, 2015
1,075 views
what is the approach of this question , Is it that first we will traverse all the pairs then find the minimum distance between all the pairs
0 votes
0 votes
0 answers
4
Harish Kumar 2 asked Dec 5, 2017
560 views
Is there any difference between the orders we get by applying masters theorem vs Substitution method?I know the conditions where master's theorem can be applied and subst...