Given that you may have duplicates, I don't see any way around keeping some kind of record of which values have been seen that you can read out on a per-value basis. Approaches based on one variety or another of one-way hashing function (two of which were proposed and then retracted) cannot do the job on their own. It may be, however, that you can save the effort of scanning your record of seen values after populating it by combining it with a hash-like function. For example,
int find_missing_number(int array[], int n)
{
char checker[100] = {0};
int xor = XOR_OF_1_TO_100;
int i;
for(i = 0; i < n; i++) {
xor ^= (checker[array[i]] ? 0 : array[i] + 1);
checker[array[i]] = 1;
}
return xor - 1;
}
This is admittedly pretty similar to your version, but I'm more confident that it will work, and I think that it probably runs slightly faster.
Note that I do not declare any variables register -- the compiler is much better than I am at choosing which variables should live in registers and which not, and it is not obligated to take my advice on the matter in any case.
Also, the elements of the checker array have type char, allowing four times as many to reside in a CPU cache line at once than if they were type int (assuming 1-byte chars and 4-byte ints).
Note too that I avoid counting distinct values or otherwise branching inside the loop (the ternary expression can be implemented without a branch). Avoiding the counting and conditional statement will speed the case where indeed one value is missing, and might or might not in practice slow down the case where none is missing. The gain may arise from more than just having less code -- sometimes such simplifications can allow the compiler to generate more efficient instruction sequences, too.
Of course, the whole thing is junk (and the problem is not well specified) if more then one value may be missing.
O(n)operations in the worst case, wherenis the size of the array to test. You cannot do better thanO(k)in the best case, wherekis the number of distinct values in the array.xor. Also,checkerreally doesn't have to beint-sized.charorboolare quite enough.