Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in C++: O(n) Time and O(1) Space with XOR

Practice O(n) Read the full explanation

You get a vector nums of n different numbers. Each number is from 0 to n.

Exactly one number from 0 to n is not in nums. Return that missing number.

 

Example 1:

Input: nums = [4, 1, 0, 2]
Output: 3
Explanation: The array has 4 numbers, so n = 4.
Of the numbers 0 to 4, only 3 is missing.

Example 2:

Input: nums = [1, 3, 2]
Output: 0
Explanation: Here n = 3.
The numbers 1, 2 and 3 are all there.
The missing number is 0.

Example 3:

Input: nums = [0]
Output: 1
Explanation: Here n = 1, and 0 is in nums.
The missing number is 1, which is n itself.

 

Constraints:

  • n is the length of nums (nums.size()).
  • n is from 1 to 100,000.
  • Each value is from 0 to n.
  • No value appears twice.
Note:

Your algorithm should run in O(n) time and use O(1) extra space.



In Single Number, XOR made the pairs cancel: x XOR x = 0, x XOR 0 = x, and the order doesn't matter. Here no number repeats. Can you give every number that is in nums a partner to cancel with?

The indices of nums go from 0 to n - 1: add n and you have every number from 0 to n once. Start from n and XOR in every index and every value. Each value in nums meets its equal and cancels; the missing number has no partner among the values, so it is what is left.

We visit each index once, with two XORs per index: O(n) time.
We keep a single number, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    C++ · BIT MANIPULATION

    Missing Number in C++, explained

    Problem overview

    The method missingNumber receives a vector<int> named nums with n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one is absent. The method returns it.

    For nums = [3, 0, 1], n is 3 and the range is 0, 1, 2, 3. Only 2 is absent, so the answer is 2. For [0, 1] the answer is 2, which is n itself, and for [1] it is 0.

    The statement asks for O(n) time and O(1) extra space.

    Approach: let equal numbers cancel with XOR

    There are easier ways that cost more. Sorting works but takes O(n log n). A set of seen values is O(n) time but O(n) space. The sum formula n * (n + 1) / 2 minus the sum of nums also works for these limits, but XOR is the idea this lesson practices.

    XOR has three properties: x ^ x = 0, x ^ 0 = x, and the order of operands doesn't matter. So if every number but one appears twice in a long XOR, the result is the number that appears once.

    Here, no value repeats inside nums, but we can give each of them a partner. The indices 0 to n - 1 plus the number n are exactly all the numbers from 0 to n, once each. XOR all of those together with all the values in nums. Every value present in nums appears twice, once as an index (or as n) and once as a value, and cancels. The missing number appears only among the indices and n, so it survives.

    For [3, 0, 1], starting at result = 3, the lesson's code gives result as 0 after index 0, 1 after index 1, and 2 after index 2. That final 2 is the answer.

    Step by step

    1. Start result at nums.size(), which is n. The indices stop at n - 1, so n has to enter the XOR here.
    2. Loop over every index from 0 to nums.size() - 1.
    3. XOR in the index and the value: result ^= i ^ nums[i].
    4. Return result. Every present number cancelled, and the missing one is left.

    The solution in C++

    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            int result = nums.size();
            for (int i = 0; i < nums.size(); i++) {
                result ^= i ^ nums[i];
            }
            return result;
        }
    };
    

    C++ details worth knowing:

    • size() is unsigned. nums.size() returns size_t. Assigning it to an int is fine for sizes up to 100,000. Comparing int i with it converts i to unsigned, which is harmless while i is never negative (some compilers warn about the mix).
    • ^= is XOR-assign: result ^= x means result = result ^ x. Here x is the whole expression i ^ nums[i], which is evaluated first.
    • By reference. vector<int>& nums avoids copying the vector.
    • No overflow. XOR never produces a value larger than the bit width of its operands, so unlike the sum formula it cannot overflow.

    Complexity

    Time: O(n). One pass, with two XORs per element.

    Space: O(1). A single integer, result, plus the loop variable.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] every index and value cancels except the initial 2. Starting result at 0 would return 0, which is wrong.
    • The missing number is 0. For [1] the result is 0, which is a valid answer, not an error signal.
    • A single element. [0] gives 1, and [1] gives 0.
    • Unsorted input. The order of nums doesn't matter, because XOR doesn't care about order. For [9, 6, 4, 2, 3, 5, 7, 0, 1] the answer is 8.
    • Confusing index and value. Both go in: XORing only the values leaves the XOR of the whole input, not the missing number.

    Testing

    • [3, 0, 1] gives 2.
    • [0, 1] gives 2.
    • [1] gives 0.
    • [9, 6, 4, 2, 3, 5, 7, 0, 1] gives 8.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free