Skip to main content
74

Missing Number

Easybit manipulationmath

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Bit ManipulationRead the beginner guide

nums contains n distinct numbers from the range [0, n], so exactly one number of that range is missing. Return it.

Understand the problem

  • n is the length of nums. The range [0, n] has n + 1 numbers, but nums only holds n of them.
  • Distinct means no number appears twice. So exactly one number from the range is missing.
  • The numbers can be in any order.

Example 1

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

n = 3, so the range is 0, 1, 2, 3. Only 2 is missing.

Example 2

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

n = 2, so the range is 0, 1, 2. The missing one can be n itself.

Example 3

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

Constraints

  • 1 <= n <= 10^4
  • All values are distinct and within [0, n].

Tip

Aim for O(n) time and O(1) extra space.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    XOR together every number that should be there (0 to n) and every number that is there; every present number cancels itself out, leaving only the missing one.

    The simple approaches

    • Sort, then find the gap: after sorting, nums[i] should equal i; the first place it doesn't is the answer. O(n log n) time.
    • A set: put every value in a set, then check 0, 1, ..., n. O(n) time, but O(n) extra memory.

    Approach 1: the sum formula

    The numbers 0 + 1 + ... + n add up to n(n + 1) / 2. Subtract the actual sum of nums, and what's left is the missing number.

    text
    nums = [3, 0, 1], n = 3
    expected: 0 + 1 + 2 + 3 = 6
    actual:   3 + 0 + 1     = 4
    missing:  6 - 4         = 2

    O(n) time, O(1) memory. A great answer. (In languages with fixed-size integers, the sum could overflow for huge n; here it's nowhere near the limit.)

    Approach 2: XOR (the reference solution)

    XOR (^) compares two numbers bit by bit; a result bit is 1 when the two bits are different. Two facts make it useful here:

    • x ^ x = 0: any number XORed with itself cancels out.
    • x ^ 0 = x, and the order of XORs doesn't matter (you can rearrange them freely).

    So 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. The missing number appears only once (as an index), so it's all that's left.

    The loop over i only covers 0..n-1, so the result starts at n to include the last index.

    Step by step

    nums = [3, 0, 1], so n = 3. Start with missing = 3:

    inums[i]missing ^ i ^ nums[i]missing
    (start: n)3
    033 ^ 0 ^ 30
    100 ^ 1 ^ 01
    211 ^ 2 ^ 12

    Answer: 2. Everything else cancelled in pairs: 0^0, 1^1, 3^3.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One pass.
    • Memory: O(1). One variable.

    Common mistakes

    • Forgetting that n itself can be missing (Example 2). Starting the XOR (or the expected sum) without n misses that case.
    • Using nums.length - 1 as n. n is the length of nums.
    • Sorting first when O(n) is asked for.

    Going deeper

    The "XOR everything, pairs cancel" trick shows up again in Single Number, where every value appears twice except one. Whenever things come in pairs and one is unpaired, think XOR.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function missingNumber(nums) {
      // XOR of every index 0..n and every value: present numbers appear twice and cancel (x ^ x = 0).
      // Start at n, because the loop's indexes only go up to n - 1.
      let missing = nums.length
      for (let i = 0; i < nums.length; i++) missing ^= i ^ nums[i]
      return missing
    }
    ts
    export default function missingNumber(nums: number[]): number {
      // XOR of every index 0..n and every value: present numbers appear twice and cancel (x ^ x = 0).
      // Start at n, because the loop's indexes only go up to n - 1.
      let missing = nums.length
      for (let i = 0; i < nums.length; i++) missing ^= i ^ nums[i]
      return missing
    }
    python
    def missing_number(nums: list[int]) -> int:
        # XOR of every index 0..n and every value: present numbers appear twice and cancel (x ^ x = 0).
        # Start at n, because the loop's indexes only go up to n - 1.
        missing = len(nums)
        for i, value in enumerate(nums):
            missing ^= i ^ value
        return missing