Find the missing and duplicate elements in an array in linear time and constant space

后端 未结 8 1332
青春惊慌失措
青春惊慌失措 2020-11-27 14:10

You’re given an array of N 64 bit integers. N may be very large. You know that every integer 1..N appears once in the array, except there is one integer mis

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 14:46

    The XOR trick works in two passes with a read-only array.

    This avoids the problem of possible integer overflows which the sum and sum of squares solution has.

    Let the two numbers be x and y, one of which is the missing number and the other repeated.

    XOR all the elements of the array, along with 1,2,...,N.

    The result is w = x XOR y.

    Now since x and y are distinct, w is non-zero.

    Pick any non-zero bit of w. x and y differ in this bit. Say the position of the bit is k.

    Now consider a split of the array (and the numbers 1,2,...,N) into two sets, based on whether the bit at position k is 0 or 1.

    Now if we compute the XOR (separately) of the elements of the two sets, the result has to be x and y.

    Since the criteria for splitting is just checking if a bit is set of not, we can compute the two XORs of the two sets by making another pass through the array and having two variables, each of which holds the XOR of the elements seen so far (and 1,2,...N), for each set. At the end, when we are done, those two variables will hold x and y.

    Related:

    • Finding missing elements in an array which can be generalized to m appearing twice and m missing.

    • Find three numbers appeared only once which is about three missing.

提交回复
热议问题