Javascript solution (Beats 95%) explained

  • 1

    The result of XORing two duplicate numbers is always zero.

    So, if we know that just one number is missing in the array, we can just XOR all the numbers in the array by a counter starting in zero and ending in the total number of elements in the array.

    In this way, just the missing number will remain at the end, since all the duplicate ones will be cancelled.

    var missingNumber = function(nums) {
        var res = nums.length;
        for(var i = 0; i < nums.length; i++){
            res ^= i ^ nums[i];
        return res;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.