← Back to libraryQuestion 93 of 273
⌨️Java CodingIntermediate

Find the Missing Number in an Array (1..n)

📌 Definition:

An array holds n-1 distinct numbers from 1..n with exactly one missing. Find it.

📖 Detailed Explanation:

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.

💻 Solutions:
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)
🔑 Key Points:
  • Expected sum n(n+1)/2 minus actual sum
  • Use a wide type to avoid overflow
  • XOR variant is overflow-proof
  • O(n) time, O(1) space
🌍 Real-World Example:

Reconciling expected-vs-actual sets ("which sequence number failed to arrive?") is a daily data-integrity task.

🎯 Scenario-Based Interview Question:

The sum-based solution returns a wrong (even negative) value for n around 100,000 in Java. Why?