Start learning free

LESSON 590 OF 671 · BIT MANIPULATION

Missing Number in JavaScript: O(n) Time, O(1) Space with XOR

Practice O(n) Read the full explanation

You get an array 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.length).
  • 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

    JAVASCRIPT · BIT MANIPULATION

    Missing Number in JavaScript, explained

    Problem overview

    The method missingNumber(nums) receives an array of n distinct numbers, each between 0 and n. The range from 0 to n holds n + 1 numbers, so exactly one is absent. The method returns it.

    For [3, 0, 1], n is 3, so the range is 0, 1, 2, 3. The numbers 0, 1 and 3 are present, so the answer is 2. The missing number can be n itself, as in [0, 1] (answer 2), or 0, as in [1] (answer 0).

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

    Approach: let XOR cancel the numbers that are present

    A set of the values gives O(n) time but O(n) space, and sorting costs O(n log n). XOR lets you do both in one pass with a single variable.

    XOR (^) compares bits: the result bit is 1 where the two bits differ. Three facts matter: x ^ x is 0, x ^ 0 is x, and the order of the operands doesn't matter. So when you XOR a collection of numbers, any number that appears twice cancels out, and what remains is the XOR of the numbers that appear once.

    Here nothing repeats, but you can create the pairs yourself. The indices of nums go from 0 to n - 1. Add n and you have every number from 0 to n exactly once. XOR all of those numbers together with all the values in nums. Each value in nums appears once among the indices-plus-n and once among the values, so it cancels. The missing number appears only among the indices-plus-n, so it is what is left.

    For [3, 0, 1], result starts at 3 and holds these values after the start and after each index:

    [3, 0, 1, 2]
    

    The final value, 2, is the missing number.

    Step by step

    1. Create result with let, starting at nums.length, which is n. The indices stop at n - 1, so n goes in at the start.
    2. Loop over every index i from 0 to nums.length - 1.
    3. XOR both the index and the value into result with result ^= i ^ nums[i].
    4. Return result.

    The solution in JavaScript

    class Solution {
        /**
        * @param {number[]} nums
        * @return {number}
        */
        missingNumber(nums) {
            let result = nums.length;
            for (let i = 0; i < nums.length; i++) {
                result ^= i ^ nums[i];
            }
            return result;
        }
    }
    

    JavaScript details worth knowing:

    • result ^= i ^ nums[i] means result = result ^ (i ^ nums[i]). Because XOR is associative, it makes no difference whether you XOR the index and the value into result one after the other or together.
    • XOR works on 32-bit integers. JavaScript converts both operands to signed 32-bit integers first. The lesson's numbers go up to 100,000, so they fit with room to spare.
    • Do not use + and - by accident with XOR. ^ is the XOR operator in JavaScript. It is not exponentiation: use ** for powers.

    Complexity

    Time: O(n). The loop runs n times with two XORs per pass.

    Space: O(1). Only result and the loop variable are kept.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] the indices are 0 and 1, and n is only in result from the start. Starting result at 0 would return 0 instead of 2. That is why it starts at nums.length.
    • The missing number is 0. For [1] the method returns 0.
    • Smallest input. [0] has n = 1 and returns 1.
    • Order of the input. It doesn't matter: [9, 6, 4, 2, 3, 5, 7, 0, 1] returns 8.
    • Sum instead of XOR. Computing n * (n + 1) / 2 minus the sum of nums also works, but the sum of 100,000 numbers is still far below JavaScript's safe integer limit, so it is a matter of taste here. XOR needs no arithmetic at all.
    • Sorting first. Sorting with no comparator orders numbers as strings: [10, 9, 1].sort() gives [1, 10, 9]. If you take the sorting route, pass (x, y) => x - y.

    Testing

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