An array holds n-1 distinct numbers from 1..n with exactly one missing. Find it.
Use the arithmetic series: the expected sum of 1..n is n(n+1)/2; subtract the actual array sum and the difference is the missing number. Use a wide type to avoid overflow, or XOR all of 1..n with all elements so pairs cancel and the missing value remains.
public static int missing(int[] a, int n) {
long expected = (long) n * (n + 1) / 2, actual = 0;
for (int x : a) actual += x;
return (int) (expected - actual);
}function missing(a, n) {
const expected = n * (n + 1) / 2;
return expected - a.reduce((s, x) => s + x, 0);
}def missing(a, n):
return n * (n + 1) // 2 - sum(a)Reconciling expected-vs-actual sets ("which sequence number failed to arrive?") is a daily data-integrity task.
The sum-based solution returns a wrong (even negative) value for n around 100,000 in Java. Why?