sagelearnai

Missing Number

Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #268

nums contains n distinct numbers taken from the range 0 … n, so exactly one number in that range is missing. Return it, using O(1) extra space.

Examples

text
nums = [3, 0, 1]                     →  2
nums = [0, 1]                        →  2
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]   →  8

Hints

  1. The sum 0 + 1 + … + n is n(n+1)/2. Subtract the actual sum.
  2. Or XOR all indices 0..n with all values; every present number cancels.

Approach

XOR together every index 0 … n and every value in nums. Each number that's present appears twice (once as an index, once as a value) and cancels, leaving only the missing number. The Gauss-sum approach n(n+1)/2 − sum(nums) is equally good (watch overflow in fixed-width languages).

Complexity

Time: O(n). Space: O(1).

Python solution
def missingNumber(nums):
    r = len(nums)
    for i, x in enumerate(nums):
        r ^= i ^ x
    return r
JavaScript solution
function missingNumber(nums) {
  let r = nums.length;
  for (let i = 0; i < nums.length; i++) r ^= i ^ nums[i];
  return r;
}