Searching two arrays for matches, no extra memory

后端 未结 4 505
暖寄归人
暖寄归人 2021-02-02 16:09

I had an interview the other day with Amazon, and a question they asked me was pertaining to the following problem.

Given 2 integer arrays, containing any number of elem

4条回答
  •  温柔的废话
    2021-02-02 16:40

    I believe this is possible to do in-place with O(1) extra space. I make use of the additional assumption that the elements in the arrays are mutable as well as swappable, but I believe with careful accounting the mutability assumption could be removed for this particular problem.

    The basic idea is to do in-place hashing. In-place hashing may be implemented by partitioning the array around a suitable percentile, say the 90th, using the O(n) median-of-medians selection algorithm. This divides the array into a small portion (about 10%) and a large portion (about 90%) whose elements are distinguishable from each other (less than the partition element or not). You can then hash from the 10% portion into the 90% portion by swapping. This hashing can be used to detect duplicates. This is O(n) for each processing of 10% of the array, so done 10 times is still O(n). I described this in much more detail, though with some hand-waving I mean to correct one day, over at this related question..

    For this particular problem, you need to do in-place hashing 3 times. First on each individual array to remove duplicates. Then, on a wrapper representing the combined arrays (if index is less than length of array 1, index into array 1, else index into array 2) to report duplicates.

提交回复
热议问题