Start learning free

LESSON 590 OF 671 · BIT MANIPULATION

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

    JAVA · BIT MANIPULATION

    Missing Number in Java, explained

    Problem overview

    The method missingNumber(int[] nums) receives n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent, and the method returns it.

    For nums = [3, 0, 1] we have n = 3, so the numbers should be 0, 1, 2 and 3. The array holds 0, 1 and 3, so the answer is 2. For [0, 1] the missing number can be n itself, 2. For [1] it can be 0.

    The target is O(n) time and O(1) extra space.

    Approach: let equal numbers cancel

    Two easy ways exist. A boolean array or a hash set records which numbers were seen, but it uses O(n) extra space. Adding up 0 + 1 + ... + n with the formula n * (n + 1) / 2 and subtracting the array's sum works in O(1) space, though it needs care with overflow for large n. This lesson uses XOR.

    XOR has three properties that matter here: x ^ x = 0, x ^ 0 = x, and the order of operands doesn't matter. So when a value appears twice in a chain of XORs, the two copies cancel, whatever else is in the chain.

    Now build a chain in which every number from 0 to n appears once from a known source, and every value of nums appears once more. The indices of nums run from 0 to n - 1, and adding n gives every number from 0 to n exactly once. Then XOR in every value of nums. Each value that is present meets its equal and cancels. The missing number has no partner among the values, so it is the only one left.

    For nums = [3, 0, 1], result starts at 3, and each pass of the loop changes it like this:

    start 3
    i=0 nums[i]=3 result=0
    i=1 nums[i]=0 result=1
    i=2 nums[i]=1 result=2
    

    The method returns 2, which is the missing number.

    Step by step

    1. Create result as an int and start it at nums.length, which is n. The indices stop at n - 1, so n has to be put in here.
    2. Visit every index with a for loop from 0 while i < nums.length.
    3. XOR both the index and the value into result with ^=. The index supplies the numbers 0 to n - 1 and the value cancels its equal.
    4. Return result after the loop.

    The solution in Java

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

    The Java details worth a closer look:

    • ^ is XOR, not a power. In Java ^ on integers is bitwise exclusive OR. There is no power operator; Math.pow does that.
    • ^= evaluates the right side first. result ^= i ^ nums[i] means result = result ^ (i ^ nums[i]). Since XOR is associative, it makes no difference whether the index and the value are combined first.
    • No overflow. XOR never carries, so the result always fits in an int. The sum-based method can overflow for large n, and this one cannot.
    • nums.length is a field. For arrays it has no parentheses, unlike size() on a list.

    Complexity

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

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

    Edge cases and common mistakes

    • The missing number is n. For [0, 1], result starts at 2, every other number cancels, and the method returns 2. If result started at 0 instead, n would never be included and this case would fail.
    • The missing number is 0. For [1] the method returns 0. XOR with 0 changes nothing, and the result is still correct.
    • Looping to n instead of n - 1. nums[n] doesn't exist and throws an ArrayIndexOutOfBoundsException. The array has indices 0 to n - 1.
    • Using + or - by mistake. Only XOR makes equal numbers cancel by themselves. Mixing operators gives wrong answers.
    • Relying on sorted input. The array can be in any order. Because XOR is order-independent, nothing needs sorting.

    Testing

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