Find duplicate element in array in time O(n)

前端 未结 24 3042
余生分开走
余生分开走 2020-11-27 10:07

I have been asked this question in a job interview and I have been wondering about the right answer.

You have an array of numbers from 0 to n-1, one o

24条回答
  •  情话喂你
    2020-11-27 10:47

    This is an alternative solution in O(n) time and O(1) space. It is similar to rici's. I find it a bit easier to understand but, in practice, it will overflow faster.

    Let X be the missing number and R be the repeated number.

    1. We can assume the numbers are from [1..n], i.e. zero does not appear. In fact, while looping through the array, we can test if zero was found and return immediately if not.

    2. Now consider:

      sum(A) = n (n + 1) / 2 - X + R
      
      product(A) = n! R / X
      

    where product(A) is the product of all element in A skipping the zero. We have two equations in two unknowns from which X and R can be derived algebraically.

    Edit: by popular demand, here is a worked-out example:

    Let's set:

    S = sum(A) - n (n + 1) / 2
    P = n! / product(A)
    

    Then our equations become:

    R - X = S
    X = R P
    

    which can be solved to:

    R = S / (1 - P)
    X = P R = P S / (1 - P)
    

    Example:

    A = [0 1 2 2 4]
    
    n = A.length - 1 = 4
    S = (1 + 2 + 2 + 4) - 4 * 5 / 2 = -1
    P = 4! / (1 * 2 * 2 * 4) = 3 / 2
    
    R = -1 / (1 - 3/2) = -1 / -1/2 = 2
    X = 3/2 * 2 = 3
    

提交回复
热议问题