find if two arrays contain the same set of integers without extra space and faster than NlogN

前端 未结 14 823
盖世英雄少女心
盖世英雄少女心 2020-12-02 17:27

I came across this post, which reports the following interview question:

Given two arrays of numbers, find if each of the two arrays have the same s

14条回答
  •  情书的邮戳
    2020-12-02 18:06

    Here is a co-rp algorithm:

    In linear time, iterate over the first array (A), building the polynomial Pa = A[0] - x)(A[1] -x)...(A[n-1] - x). Do the same for array B, naming this polynomial Pb.

    We now want to answer the question "is Pa = Pb?" We can check this probabilistically as follows. Select a number r uniformly at random from the range [0...4n] and compute d = Pa(r) - Pb(r) in linear time. If d = 0, return true; otherwise return false.

    Why is this valid? First of all, observe that if the two arrays contain the same elements, then Pa = Pb, so Pa(r) = Pb(r) for all r. With this in mind, we can easily see that this algorithm will never erroneously reject two identical arrays.

    Now we must consider the case where the arrays are not identical. By the Schwart-Zippel Lemma, P(Pa(r) - Pb(r) = 0 | Pa != Pb) < (n/4n). So the probability that we accept the two arrays as equivalent when they are not is < (1/4).

提交回复
热议问题