A new approach. Let m be the missing number and r be the repeating number. After going through the array once, let X be the result of XOR inputting the array entries along with indices 1 - n . Then X = m XOR r . In particular, it is not 0 . Let b be any nonzero bit of X (you only need to select one, and one exists, since X not 0 ). After going through the array, let Y be the result of XOR inputting the array entries and indices 1 to n , where bit b is 0 and let Z be the result of XOR entering the array entries and indices 1 to n , where bit b is 1 . Then Y and Z save m and r , so all that remains is to make the final pass to see what is in the array.
Total area: 4 (or 3 if you reuse X for b )
Total time: 7 passes (or 3 if you are doing indexes simultaneously with an array and calculating Y and Z at the same time.
Therefore, O(1) space and O(n) time.
source share