Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Doesn't this work?:</p> <p>You can compute the rank of a number in linear time as long as <code>A</code> and <code>B</code> are sorted. The technique you use for computing the rank can also be used to find all things in <code>A+B</code> that are between some lower bound and some upper bound in time linear the size of the output plus <code>|A|+|B|</code>.</p> <p>Randomly sample <code>n</code> things from <code>A+B</code>. Take the median, say <code>foo</code>. Compute the rank of <code>foo</code>. With constant probability, <code>foo</code>'s rank is within <code>n</code> of the median's rank. Keep doing this (an expected constant number of times) until you have lower and upper bounds on the median that are within <code>2n</code> of each other. (This whole process takes expected linear time, but it's obviously slow.)</p> <p>All you have to do now is enumerate everything between the bounds and do a linear-time selection on a linear-sized list.</p> <p>(Unrelatedly, I wouldn't excuse the interviewer for asking such an obviously crappy interview question. Stuff like this in no way indicates your ability to code.)</p> <p><strong>EDIT</strong>: You can compute the rank of a number <code>x</code> by doing something like this:</p> <pre><code>Set i = j = 0. While j &lt; |B| and A[i] + B[j] &lt;= x, j++. While i &lt; |A| { While A[i] + B[j] &gt; x and j &gt;= 0, j--. If j &lt; 0, break. rank += j+1. i++. } </code></pre> <p><strong>FURTHER EDIT</strong>: Actually, the above trick only narrows down the candidate space to about n log(n) members of <code>A+B</code>. Then you have a general selection problem within a universe of size n log(n); you can do basically the same trick one more time and find a range of size proportional to sqrt(n) log(n) where you do selection.</p> <p>Here's why: If you sample k things from an n-set and take the median, then the sample median's order is between the (1/2 - sqrt(log(n) / k))th and the (1/2 + sqrt(log(n) / k))th elements with at least constant probability. When n = |A+B|, we'll want to take k = sqrt(n) and we get a range of about sqrt(n log n) elements --- that's about |A| log |A|. But then you do it again and you get a range on the order of sqrt(n) polylog(n).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload