Sunday, August 19, 2007

Missing And Duplicate number algorithm

Recently in the MSTechExperts forum, a question was posted to have an algorithm which would find the duplicate and missing number in an array of “unsorted set of continuous numbers “(1 to N). My solution for the same is given below.

1. Find RealSum = ( sum of all numbers in array )
2. Find RealProduct = ( product of all numbers in array )
3. Find ExpectedSum = n*(n+1) / 2 where n is number of integers
4. Find ExpectedProduct = n!

Equation 1 : X - Y = (RealSum - ExpectedSum)
Equation 2 : X/Y = (RealProduct / ExpectedProduct)
ie X - Y * ( RealProduct/ExpectedProduct ) = 0

Solve this equation.
X is the duplicated number
Y is the missing number

Visit www.mstechexperts.org for more interesting questions like this.