Let's re-word the problem: we're to find two elements, such that abs(x-y) <= c
, where c
is a constant, that we can find in O(n)
time. (Indeed, we can compute both max(A)
and min(A)
in linear time and just assign c=(max-min)/n
).
Let's imagine we have a set of buckets, so that in first bucket elements 0<=x<c
are placed, in the second bucket elements c<=x<=2c
are placed, etc. For each element, we can determine its bucket for O(1)
time. Note that the number of buckets occupied will be not more than the number of elements in array.
Let's iterate the array and place each element to its bucket. If in the bucket we're going to place it, there already is another element, then we've just found the proper pair of x
and y
!
If we've iterated the whole array and every element has fallen into its own bucket, no worries! Iterate the buckets now (there is not more than n
buckets, as we've said above) and for each bucket element x
, if in the next bucket y
element is such that abs(x-y)<=c
, then we've found the solution.
If we iterated all the buckets and found no proper elements, then there is no solution. OMG, I really missed that pigeonhole stuff (see the other answer).
Buckets may be implemented as a hash map, where each bucket holds one array index (placing element in bucket will look like this: buckets[ a[i] / c] = i
). We compute c
in O(n)
time, assign items to buckets in O(n)*O(1)
time (O(1)
is access to hash map), traverse buckets in O(n)
time. Therefore, the whole algorithm is linear.