Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in Rust: O(n) Time and O(1) Space with XOR

Practice O(n) Read the full explanation

You get an array nums of n different numbers. Each number is from 0 to n.

Exactly one number from 0 to n is not in nums. Return that missing number.

 

Example 1:

Input: nums = [4, 1, 0, 2]
Output: 3
Explanation: The array has 4 numbers, so n = 4.
Of the numbers 0 to 4, only 3 is missing.

Example 2:

Input: nums = [1, 3, 2]
Output: 0
Explanation: Here n = 3.
The numbers 1, 2 and 3 are all there.
The missing number is 0.

Example 3:

Input: nums = [0]
Output: 1
Explanation: Here n = 1, and 0 is in nums.
The missing number is 1, which is n itself.

 

Constraints:

  • n is the length of nums (nums.len()).
  • n is from 1 to 100,000.
  • Each value is from 0 to n.
  • No value appears twice.
Note:

Your algorithm should run in O(n) time and use O(1) extra space.



In Single Number, XOR made the pairs cancel: x XOR x = 0, x XOR 0 = x, and the order doesn't matter. Here no number repeats. Can you give every number that is in nums a partner to cancel with?

The indices of nums go from 0 to n - 1: add n and you have every number from 0 to n once. Start from n and XOR in every index and every value. Each value in nums meets its equal and cancels; the missing number has no partner among the values, so it is what is left.

We visit each index once, with two XORs per index: O(n) time.
We keep a single number, so the extra space is O(1).
STEP 1 OF 4
    Ctrl + Enter to check

    RUST · BIT MANIPULATION

    Missing Number in Rust, explained

    Problem overview

    The function missing_number receives a vector nums of n distinct integers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent, and the function returns it.

    For nums = [3, 0, 1], n is 3 and the range is 0, 1, 2, 3. Only 2 is absent, so the answer is 2. For [0, 1] the answer is 2, which is n itself, and for [1] the answer is 0.

    Approach: cancel pairs with XOR

    Sorting the vector or storing every value in a set would find the gap, but the lesson asks for O(n) time and O(1) extra space, which rules out both. The sum formula n * (n + 1) / 2 minus the sum of the vector would also work, but XOR avoids any worry about large totals.

    XOR has three properties that matter: x ^ x = 0, x ^ 0 = x, and the order doesn't matter. So when a value appears twice in an XOR chain, the two copies cancel out.

    The idea is to give every value in nums a partner. The indices of nums are 0 to n - 1. Add n to those and the list holds each number from 0 to n exactly once. XOR together all those numbers and all the values of nums. Every number that is in nums appears twice and cancels. The missing number appears once and is what remains.

    For nums = [3, 0, 1], result starts at 3. After the pass for index 0 (value 3) it is 0, after index 1 (value 0) it is 1, and after index 2 (value 1) it is 2. That is the missing number.

    Step by step

    1. Start result at nums.len(). This puts n into the XOR chain, since the indices stop at n - 1. The length is a usize, so as i32 converts it to the type of the values.
    2. Loop i over 0..nums.len(). The range stops before the length, so i takes every index.
    3. XOR the index and the value into result. The index also needs as i32, because XOR works on two numbers of the same type.
    4. Return result as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn missing_number(nums: Vec<i32>) -> i32 {
            let mut result = nums.len() as i32;
            for i in 0..nums.len() {
                result ^= i as i32 ^ nums[i];
            }
            result
        }
    }
    

    Rust details worth knowing:

    • Precedence. In i as i32 ^ nums[i], the as cast binds tighter than ^, so it is (i as i32) ^ nums[i]. The compound assignment ^= then applies to the whole right-hand side, so the line means result = result ^ ((i as i32) ^ nums[i]).
    • usize to i32. An as cast between integer types never fails: it truncates silently if the value doesn't fit. Here every index is at most 100,000, so nothing is lost.
    • Indexing by position. The loop reads nums[i], which panics for an index out of range. The range 0..nums.len() keeps every index valid.

    Complexity

    Time: O(n). The loop visits each index once and does two XORs per pass.

    Space: O(1). The function keeps only result and the loop variable.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1], the indices are 0 and 1, the values are 0 and 1, and the starting result of 2 never cancels, so the function returns 2.
    • The missing number is 0. For [1], the XOR is 1 ^ (0 ^ 1), which is 0.
    • Forgetting the starting n. Starting result at 0 leaves n out of the chain, so the function returns the missing number XOR n: for [3, 0, 1] that is 1 instead of 2.
    • Mixing types. result ^= i ^ nums[i] without casts does not compile, since i is a usize and nums[i] is an i32.
    • Using the loop on a non-distinct input. The trick relies on every value being distinct and in range, as the lesson promises. With a repeated value, the cancellation no longer isolates a single number.

    Testing

    • nums = [3, 0, 1] gives 2.
    • nums = [0, 1] gives 2.
    • nums = [1] gives 0.
    • nums = [9, 6, 4, 2, 3, 5, 7, 0, 1] gives 8.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free