Let us reformulate the problem: we must find two elements such that abs(xy) <= c , where c is the constant that we can find in O(n) time. (Indeed, we can calculate both max(A) and min(A) in linear time and simply assign c=(max-min)/n ).
Suppose we have a set of buckets, so that 0<=x<c in the first bucket elements are placed, c<=x<=2c in the second bucket element, etc. For each element, we can define its bucket for O(1) time. Please note that the number of occupied buckets will not exceed the number of elements in the array.
Let iterate over the array and put each element in its bucket. If we are going to place it in the bucket, then there is already another element, then we just found the correct pair of x and y !
If we repeated the entire array, and each element fell into its own bucket, do not worry! Now change the buckets (no more than n , as we said above), and for each element bucket x , if the next element y contains such an element that abs(xy)<=c ve found a solution.
If we repeated all the buckets and did not find suitable elements, then there is no solution. OMG, I really missed this stuff for pigs (see another answer ).
Buckets can be implemented as a hash map, where each bucket contains one array index (placing an item in the bucket will look like this: buckets[ a[i] / c] = i ). We calculate c in O(n) time, assign positions to buckets in O(n)*O(1) time ( O(1) is access to the hash map), move the buckets in O(n) time. Therefore, the entire algorithm is linear.
Pavel shved
source share