retagged by
505 views
4 votes
4 votes

Consider a sorted array of $p$ numbers. What would be the time complexity of the best known algorithm to find a pair $x$ and $y$ such that $\left | x-y \right |$ $=$ $m$ (where $m$ is a positive integer) ?

  1.   $O$$\left ( \log p \right )$
  2.   $O$$\left ( p \right )$ but not in $O$$\left ( \log p \right )$
  3.   $O$$\left ( p^{2} \right )$
  4.   $O$$\left ( p\log p \right )$but not in $O$$\left ( p \right )$
retagged by

1 Answer

Best answer
10 votes
10 votes
Given array is sorted. Let two pointers $i$ and $j$, both be pointing to the first element.
If the difference of elements $arr\left [ i \right ]$ and $arr\left [j \right ] > m$, increment $i$.
If the difference of elements $arr\left [ i \right ]$ and $arr\left [ j \right ]$ is $< m$, increment $j$.
Otherwise, we found the exact difference $m$ at indices $i$  and $j$.

This procedure will take $O$$\left ( p \right )$time but not $O$$\left ( \log p \right )$.

option $B$
edited by
Answer:

Related questions

3 votes
3 votes
1 answer
3
Bikram asked May 14, 2017
307 views
What is the worst case time complexity to calculate the depth of a directed acyclic graph (DAG) with ‘$V$’ vertices and ‘$E$’ edges?$O\left ( V+E \right )$$O\left...