2 minute read

Missing number.

Problem description

Taken directly from LeetCode.

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.

Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • 0 <= nums[i] <= n
  • All the numbers of nums are unique.

Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

Solution type

Bit operations, plus some math if you want.

Solution

XOR is the key. Think of a ^ b as flipping switch a if b = 1: if a = 0, b = 1, then a ^ b = 1, the complement of 0. If a = 1, b = 1, then a ^ b = 0 and again you have this flip. If b = 0, then nothing changes in the output.

with 32-bit wide inputs, we can just think of this as flipping 32 switches. Two questions arise: what would be the state of the switches if we XOR’d all numbers from 0 up to n, and what would be the state of the switches if we XOR’d all numbers in nums? We can answer this question by just doing all those XOR operations in a loop and accumulating the result. If we XOR the two results, then that will give us the number we XOR’d by in the former but not the latter.

Here’s a little more proof on the math: any number XOR’d by itself is 0. If a is the result of XOR’ing all numbers from 0 to n and b is the result of XOR’ing all numbers from 0 to n except one of those numbers, then we can rearrange the XOR operations so that all factors in a and b cancel each other out except for the one factor in a that does not have a twin in b. Therefore, a ^ b returns this one untwinned number.

int missingNumber(vector<int>& nums) {
    int xor_n = 0, xor_nums = 0;
    for (int i = 0; i < nums.size(); ++i) {
        xor_n ^= i;
        xor_nums ^= nums[i];
    }
    xor_n ^= nums.size();

    return xor_n ^ xor_nums;
}

Leave a comment

Your email address will not be published. Required fields are marked. *

Loading...