DSA sheet / Introductory

Missing Number

easy about 10 min mathxor
Open on CSES

The problem in brief

You are given n, then n - 1 distinct integers, all taken from 1 to n. Exactly one number from that range is missing; print it. n can be as large as 200 000.

Try it

Tab indents; press Esc, then Tab, to leave the box. Ctrl+Enter runs.

Hints

Stuck? Reveal one hint at a time. Each nudges without giving away the next.

The walkthrough

Spoilers ahead: open a section only after you have given the hints a fair try.

How to think

The brute force is to mark every number you see in a boolean array and scan for the unmarked one. That is O(n) time and memory and it works. The habit worth building is asking “can I keep a single summary of the whole input instead of the input itself?”. The set of present numbers is a lot of information; you only need one number out of it.

Whenever a problem says “exactly one thing is different from a known baseline”, a running aggregate (sum, XOR, count) of the baseline minus the same aggregate of the data isolates the difference. That is the pattern: compute the aggregate of what should be there, subtract or cancel what is there.

Intuition

Imagine paying a bill of 1 + 2 + … + n and being handed all the coins but one. The shortfall is exactly the missing coin. XOR works like a “cancelling” version of the same idea: every number that appears twice (once in the expected list, once in the data) vanishes, and only the missing one is left.

Approach
  1. Read n and compute expected = n(n + 1) / 2 in a 64-bit integer.
  2. Read the n - 1 numbers, subtracting each from expected (or adding them to a running sum).
  3. What remains is the missing number.

Pitfall: n(n + 1)/2 is about 2 * 10^10 for n = 200 000, which overflows a 32-bit int. Use long long / long. Python is safe by default, and JavaScript numbers hold integers exactly up to 2^53, so they are fine here too. The XOR version avoids the issue entirely because the result never exceeds n.

Complexity

O(n) time to read the input, O(1) extra memory.

Solutions

Written from scratch and checked by compiling and running each one against a brute force on random inputs. Fast input/output, the way you would submit it.

Show solutions (C++17, Python 3, Java 17, Node.js)
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    long long n;
    cin >> n;
    long long rest = n * (n + 1) / 2;
    for (int i = 0; i < n - 1; i++) {
        long long x;
        cin >> x;
        rest -= x;
    }
    cout << rest << "\n";
    return 0;
}

Problem: CSES Problem Set (Antti Laaksonen, University of Helsinki), CC BY-NC-SA 4.0. The explanations and code above are original (© Anupam Kumar).

Related problems

Back to the sheet