Possible Duplicate:
Easy interview question got harder: given numbers 1..100, find the missing number(s)
**No, it is a duplicate !!! some numbers in the given array may be duplicated. Please refer to the example at the bottom of my post. thanks !!! **
Given an array of size n, containing numbers in the range 1 to n. Each number is present at least once except for 2 numbers. Find the missing numbers.
e.g. A = [2, 4, 5, 4, 6, 5], missing numbers are 3 and 1.
My solutions:
sort A with O(n lg n) then scan.
Or, scan and set up a new bool array B to mark whether a number in the given array appears or not, e.g. B[A[i]] = true or false. Then, scan the bool array to the false element whose index is the missing element. Time O(n) but space O(n).
Are there solutions of O(n) in time and O(1) in space ?
Attention: the method of sum and multiplication does not work.
For example, given A [2, 3, 2, 3], the missing numbers are : 1 and 4.
Suppose missing numbers are x and y.
we cannot get:
x + y = sum of 1 to n - sum of A
x * y = product of 1 to n / product of A
1 + 4 != 10 - 10
1 * 4 != 24/36
thanks