views:

555

answers:

2

Hi,

I need to find 2 elements in an unsorted array such that the difference between them is less than or equal to (Maximum - Minimum)/(number of elements in the array).

In O(n).

I know the max and min values.

Can anyone think of something?

Thank you!

+3  A: 

Step 1: Use Bucket Sort. Don't sort the individual buckets.

Should be pretty obvious what to do from here, and how to size the buckets.

Brian
This is the correct solution. I'm not sure about "pretty obvious", the one thing to worry about is there are two situations to check: one where one pidgeonhole has more than one pidgeon, and one where all pidgeonholes have exactly 1 pidgeon.
Jimmy
+1 but it isn't obvious first time I read it...
chakrit
Sid Datta goes into more detail.
Brian
+1  A: 
  1. Number of buckets = 2n.

    values in each bucket = (min + k((max-min)/2n)) <= value < (min + (k+1)((max-min)/2n)).

    0 <= k < 2n

    Range of each bucket = ((max-min)/2n)

  2. Assign each element into buckets. Dont sort inside buckets.

  3. If any bucket has more than 1 element, the maximum possible difference between them is ((max-min)/2n) . Hence you have your answer.

  4. If any two consecutive buckets have more than zero elements each, maximum difference between them is ((max-min)/2n)*2 = ((max-min)/n) . Hence you have your answer.

Sid Datta
this works, although you can make do with n buckets, you just have to compare consecutive values.
Jimmy
I think this misses the solution in some cases. What if the n items appear in alternate buckets, so there are never two non-empty buckets in a row, but there's one value near the "top" of bucket j, and another value near the "bottom" of bucket j+2. They're less than (max-min)/n apart.
Steve Jessop
As Jimmy says, though, in this case the buckets have fully sorted the array, meaning that you can finish with an O(n) pass to either find a solution or prove there isn't one.
Steve Jessop