InterviewPrepKit

Home / Coding / Bit Manipulation

Missing Number

easy Original β†—
Solving tips
  • XOR insight: fold every index 0..n together with every value in nums; each present number appears as both an index and a value and cancels (x^x=0), leaving the missing number.
  • Seed the accumulator with n (or len(nums)) because enumerate only yields indices 0..n-1; then XOR i ^ num for each element.
  • Target O(n) time, O(1) space, and unlike the Gauss-sum method (expected n(n+1)/2 minus actual sum) XOR never overflows.
  • Pitfall: cover the full range 0..n inclusive (n+1 values); order doesn't matter since XOR is commutative.

Problem

You are given an array nums of n distinct integers drawn from the range [0, n] (that range holds n + 1 values, so exactly one is absent). Return the single number in [0, n] that does not appear in nums.

Examples

  • [3, 0, 1] β†’ 2 β€” n = 3, the full range is 0..3; 2 is missing.
  • [0, 1] β†’ 2 β€” n = 2, the full range is 0..2; 2 is missing.
  • [9, 6, 4, 2, 3, 5, 7, 0, 1] β†’ 8 β€” n = 9; every value 0..9 is present except 8.

Constraints

  • n == len(nums), 0 <= nums[i] <= n, and all nums[i] are distinct.
  • 1 <= n <= 10^4

Follow-up: O(n) time, O(1) extra space, and without any risk of integer overflow.

Think about it first

Hint 1 The array should contain every value in `0..n` but one. Put the present values in a set and find the one index in `0..n` that isn't there β€” correct, but O(n) space.
Hint 2 The numbers `0..n` have a known total, `n(n + 1) / 2`. Subtract the actual sum of `nums` and the missing value falls out β€” O(1) space, though the sum can overflow a fixed-width integer.
Hint 3 XOR is self-cancelling: `x ^ x = 0` and `x ^ 0 = x`. XOR together all the indices `0..n` and all the values in `nums`. Every present number shows up as both an index and a value and cancels itself; the missing number appears only as an index and survives β€” no overflow risk.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.