268. Missing Number

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let tot = nums.length * (nums.length + 1) / 2;
    let partial = 0;
    
    for (let i = 0; i < nums.length; i++) {
        partial += nums[i];
    }
    
    return tot - partial;
};

Solution (XOR)

/**
 * @param {number[]} nums
 * @return {number}
 */
var missingNumber = function(nums) {
    let tot = 0;
    
    let i = 0;
    for (; i < nums.length; i++) {
        tot = tot ^ i ^ nums[i];
    }
    
    // 0..n will always be bigger than nums by one
    tot = tot ^ i;
    
    return tot;
};

Complexity

  • Time Complexity: O(N), where N is the size of nums.
  • Space Complexity: O(1).

All Solutions