Let the array A = [a1,a2,...,an], sorted so that a1 <= a2 <= ... <=an
and we are looking for a[i] and a[j] such that a[j] - a[i] = K where K is
given.
start with a[1], and look for the first index t1 such that a[t1] >= a[1] + K
. If a[t1] = a[1] + K, we are done. Otherwise we move to a[2], and check
whether a[2] + K >= a[t1] or not. if equal, we are done, else if less, then
we move to a[3], else greater, then we move t1 to t1 + 1.
Algorithm:
left = 1, right = 1
while (right <= n) { // invariant: a[left] + K > a[right-1]
if a[left] + K == a[right] then return solution(left, right)
else if a[left] + K < a[right] then left = left + 1
else right = right + 1
}
return "no solution"