Missing Number

easy array bit manipulation math

Problem

Given an array nums of n distinct numbers drawn from 0..n with exactly one omission, return the missing one.

XOR has two handy properties: x ^ x = 0 and x ^ 0 = x. Start with n and XOR every index i together with every value nums[i]. Every present number appears twice (as an index and a value) and cancels — only the missing value survives.

Inputnums = [3, 0, 1]
Output2

def missing_number(nums):
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x
function missingNumber(nums) {
  let x = nums.length;
  for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i];
  return x;
}
class Solution {
    public int missingNumber(int[] nums) {
        int x = nums.length;
        for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
        return x;
    }
}
int missingNumber(vector<int>& nums) {
    int x = nums.size();
    for (int i = 0; i < (int)nums.size(); i++) x ^= i ^ nums[i];
    return x;
}
Time: O(n) Space: O(1)