Given an array of size N containing number from 1 to n,except one number is missing and one number is duplicated.Find Both numbers in linear time.
This problem is an extension of our post of finding missing number in an array.
Solution : Let missing number be x and duplicate number be y. We know that sum of of numbers from 1 to n is n*(n+1)/2. we can scan all numbers of array in O(n) time and get the sum of all numbers. This sum would be:
We also know the sum of squares of first n numbers is n*(n+1)*(2n+1)/6. Now we calculate the sum of squares of elements in the array, which would sum up to
S2 = n*(n+1)*(2n+1)/6 – x^2+y^2;
We have got two equations and two unknown variables x and y.We can solve the equations and find the value of x and y.