We can use the fact that elements are from 0 to n-1 and put each element in its “correct” (i == a[i]) position.
Since one element is missing, one position will not have correct element in it. Instead it will have duplicate element.
For example, for given array [5,3,0,3,1,2] we get [0,1,2,3,3,5]. Now it’s obvious that number 4 is missing and 3 occupies its space.
We have to be careful not to end up in infinite loop. We stop swapping when the element we swap with is the same as the current element.
int i = 0; int lastMismatch = 0; while (i < a.length) { while (i != a[i] && a[a[i]] != a[i]) { swap(a, i, a[i]); }
if (i != a[i]) { lastMismatch = i; }
i++; }
System.out.println(lastMismatch + " is missing and " + a[lastMismatch] + " is duplicate");
The algorithm is O(1) space and O(n) running time, since each swap puts one element in its correct position.