Skip to main content
Easy Bit Manipulation High frequency

Missing Number

Open on LeetCode

Approach Summary

XOR of all indices (0..n) XOR all array values. The missing number is what remains. Or use Gauss sum formula.

Full Solution & Approach

XOR is the clean O(1)-space solution. XOR every index with every value and also XOR in n. Since a ^ a = 0, every value that exists in the array cancels with its index, leaving only the index — the number — that never appeared. Concretely, result starts as n (the missing number must lie in [0, n]), then result ^= i ^ nums[i] for every i. Pairs where nums[i] === i cancel out entirely; the missing value has no counterpart, so it survives. Alternative solutions: sort and scan (O(n log n)), the sum formula (risky overflow for huge n), or a boolean array (O(n) space). The XOR version is optimal in both time and space and generalizes to other find-the-odd-one-out problems.

Single pass with constant-time XOR per element — O(n) time and O(1) space.

Solution Code

Solution

def missing_number(nums: list[int]) -> int:
    result = len(nums)
    for i, n in enumerate(nums):
        result ^= i ^ n
    return result

Edge Cases to Watch

  • Missing number is 0 — XOR handles it since 0 is its own identity
  • Missing number is n (the largest) — the result initialized to n catches it
  • Single element [0] — missing is 1; [1] — missing is 0

How to Recognize This Pattern

  • Find missing number in 0..n
  • XOR or math sum

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)

Tags

Array Math Bit Manipulation Sorting

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee