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

后端 未结 8 1358
青春惊慌失措
青春惊慌失措 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:24

    The solution proposed by BrokenGlass covers the case for two unknowns (corresponding to one duplicate number and one missing number), using two formulas:

    sum1

    and

    sum2

    The formulas yield the generalized harmonic number of orders n of -1 and -2, respectively. (Power series)

    This solution is generalizable for 3 unknowns by including the value of generalized harmonic number of order n of -3.

    sum3

    To solve for m unknowns (duplicates and missing numbers), use m generalized harmonic numbers of orders n of -1 through -m.


    Moron notes that this approach was discussed earlier in StackOverflow at Easy interview question got harder.

提交回复
热议问题