The Problem

Given: An array nums containing n distinct numbers in the range [0, n]

Return: The only number in the range that is missing from the array

Example:

  • Input: [3,0,1] โ†’ Output: 2
  • Input: [0,1] โ†’ Output: 2
  • Input: [9,6,4,2,3,5,7,0,1] โ†’ Output: 8

Interactive Visualization

Speed: 1.0s
Phase: Initialization
Indices (0 to n):
Array Values:
XOR Accumulator (result)
0
0b0000
Code
fun missingNumber(nums: IntArray): Int {
    var result = nums.size    for (i in nums.indices) {        result = result xor i xor nums[i]    }    return result
}
Status
Ready to start
Log

How It Works

Key Insight: XOR Properties

The XOR operation has special properties that make this solution elegant:

  • Self-inverse: a ^ a = 0 (any number XOR'd with itself equals 0)
  • Identity: a ^ 0 = a (any number XOR'd with 0 equals itself)
  • Commutative: a ^ b = b ^ a (order doesn't matter)

By XORing all indices [0, n] with all array values, pairs that exist in both cancel out (become 0), leaving only the missing number.

Algorithm Steps

  1. Initialize: Set result = n (the length of the array)
  2. Iterate: For each index i from 0 to n-1:
    • XOR result with the index i
    • XOR result with the array value nums[i]
  3. Result: After all XOR operations, result contains the missing number

Why it works: We XOR all numbers from 0 to n (both as indices and including n itself) with all values in the array. Numbers that appear in both cancel out, leaving only the missing one.

Example Walkthrough

For array [3, 0, 1] (missing 2):

result = 3 (length)
i=0: result = 3 ^ 0 ^ 3 = 0
i=1: result = 0 ^ 1 ^ 0 = 1
i=2: result = 1 ^ 2 ^ 1 = 2 โ† Missing number!

Breakdown: (0^1^2^3) ^ (3^0^1) = 2
All pairs cancel except 2

Complexity Analysis

Time Complexity O(n)
Space Complexity O(1)

Single pass through the array with only a single variable for the result. This is more efficient than the sum formula approach when dealing with very large numbers (avoids potential integer overflow in some languages).

Alternative Approaches

  • Sum Formula: missing = n*(n+1)/2 - sum(nums) โ€” O(n) time, O(1) space, but may overflow
  • HashSet: Add all to set, check 0 to n โ€” O(n) time, O(n) space
  • Sorting: Sort and scan โ€” O(n log n) time, O(1) space

The XOR approach is optimal: O(n) time, O(1) space, and no overflow concerns.