Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in TypeScript: 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

    TYPESCRIPT · BIT MANIPULATION

    Missing Number in TypeScript, explained

    Problem overview

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

    For nums = [3, 0, 1], n is 3, so the numbers should be 0, 1, 2 and 3. Only 2 is absent, so the result is 2. The missing number can also be n itself, as in [0, 1] (result 2), or 0, as in [1] (result 0).

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

    Approach: give every present number a partner

    There are simpler ways. Sorting the array and scanning for the first gap costs O(n log n). A Set of the values, checked against 0 to n, is O(n) time but O(n) space. Adding up 0 to n and subtracting the array's sum also works in constant space, and this lesson uses XOR instead.

    XOR has three properties that matter here: x ^ x is 0, x ^ 0 is x, and the order of the operands doesn't matter. So when a collection of numbers is XORed together, any number that appears twice cancels out, and what remains is the XOR of the numbers that appear once.

    No number repeats in nums, so we create the repeats. The indices of the array run from 0 to n - 1, and adding n gives every number from 0 to n exactly once. If we XOR those numbers together with every value in nums, each value that is present meets its equal among the indices and cancels. The missing number appears among the indices (or as n) but not among the values, so it is the only one left.

    Here is a run on [3, 0, 1], starting with result = 3 (that is, n):

    i  nums[i]  result after i ^ nums[i] is XORed in
    0  3        0
    1  0        1
    2  1        2
    

    The result is 2, the missing number.

    Step by step

    1. Start result at nums.length, 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.length - 1.
    3. XOR in the index and the value: result ^= i ^ nums[i]. The index supplies each number from 0 to n - 1, and the value cancels the one it equals.
    4. Return result. Every number in nums went in twice and cancelled, so what is left is the missing one.

    The solution in TypeScript

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

    Some TypeScript details:

    • ^= is compound assignment. result ^= x means result = result ^ x. The right side, i ^ nums[i], is evaluated first, but since XOR is associative the grouping doesn't change the answer.
    • ^ is XOR, not a power. Exponentiation in TypeScript is **.
    • 32-bit integers. Bitwise operators convert their operands to 32-bit integers. With n up to 100,000 that is no limit.
    • Types are erased. number[] checks nothing at run time. If the array held strings, ^ would still convert them to numbers, so the types are what protects you here.

    Complexity

    Time: O(n). The loop visits each index once and does two XORs per visit.

    Space: O(1). The method keeps one number, result, and the loop variable.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] the indices are 0 and 1, the values are 0 and 1, and everything cancels except the starting n = 2. The result is 2.
    • The missing number is 0. For [1] the method returns 0: the starting 1 cancels with the value 1, and index 0 is left.
    • Starting at 0 instead of nums.length. Then n is never XORed in, and the answer is wrong whenever the missing number is not n. For [0] the correct answer is 1, but starting from 0 the method would return 0.
    • Looping to nums.length inclusive. That would read nums[n], which is undefined, and i ^ undefined treats it as 0, which silently changes the result.
    • Assuming a sorted input. Nothing in the method depends on order: [9, 6, 4, 2, 3, 5, 7, 0, 1] returns 8.

    Testing

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