Missing Number

Difficulty: Easy

A list holds n distinct numbers from the range 0 to n (inclusive). That range has n + 1 values, so exactly one is missing. Find it.

Examples

Input: nums = [3, 0, 1]
Output: 2

n = 3 (the list has 3 elements), so the full range is 0-3. Every value shows up except 2.

Input: nums = [0, 1]
Output: 2

n = 2, full range is 0-2. 0 and 1 are present, so 2 is missing.

Input: nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]
Output: 8

n = 9, full range is 0-9. Every value is present except 8.

Constraints

  • n == nums.length

  • 1 <= n <= 10^4

  • 0 <= nums[i] <= n

  • All the numbers in nums are unique.

Approach

The direct way puts every value in a hash set, then checks each number from 0 to n until one is missing.

XOR avoids the extra set. XOR together every index from 0 to n and every value in the list. Include n itself: the list only has indexes 0 to n-1, but the values go up to n.

Each present value pairs with a matching index and cancels to 0, in any order. Only the missing number has no partner, so it's what's left.

Solutions

Brute Force - Hash Set of Present Values

Put every value into a hash set. Check each number from 0 to n in order; the first one not in the set is missing.

function missingNumber(nums) {
  const present = new Set(nums);
  const n = nums.length;

  for (let i = 0; i <= n; i++) {
    if (!present.has(i)) return i;
  }
}

Time: O(n) · Space: O(n)

Optimal - XOR Indexes and Values Together

XOR every index and every value into one result. Start the result at n, because the loop's indexes only reach n-1. Each present value cancels with its index, leaving the missing number.

function missingNumber(nums) {
  let result = nums.length; // accounts for index n, which has no array slot

  for (let i = 0; i < nums.length; i++) {
    result ^= i ^ nums[i];
  }

  return result;
}

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