Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in C#: O(n) Time, 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.Length).
  • 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

    C# · BIT MANIPULATION

    Missing Number in C#, explained

    Problem overview

    The method MissingNumber receives an int[] nums of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one is absent. The method returns it.

    For [3, 0, 1], n is 3, the full range is 0, 1, 2, 3, and the missing number is 2. For [0, 1] it is 2, which is n itself. For [1] it is 0.

    Approach: let the pairs cancel

    Sorting the array and looking for the gap works, but it costs O(n log n). A hash set gives O(n) time but needs O(n) extra space. The lesson asks for O(n) time and O(1) space, and XOR does that.

    XOR (^) has three properties that matter here: x ^ x = 0, x ^ 0 = x, and the order of operands doesn't matter. So if every number appears an even number of times in a long XOR chain, everything cancels, and a number that appears an odd number of times is what remains.

    Build a chain in which every number from 0 to n appears once from the "expected" side, and every value in nums appears once from the "actual" side. The expected side is the indices 0 to n - 1 plus n itself. A value present in nums appears on both sides and cancels. The missing number appears only on the expected side, so it is what is left.

    Step by step

    1. Start result at nums.Length, which is n. The indices stop at n - 1, so n has to be added at the start.
    2. Loop i from 0 while i < nums.Length. The indices 0 to n - 1, together with the n already in result, are every number from 0 to n once.
    3. XOR both i and nums[i] into result with ^=.
    4. Return result.

    Tracing [3, 0, 1], result starts at 3 and after each index is:

    i=0 result=0
    i=1 result=1
    i=2 result=2
    

    The last value, 2, is the missing number. At i = 0, for instance, the 3 in result met the 3 in nums[0] and cancelled.

    The solution in C#

    class Solution {
        public int MissingNumber(int[] nums) {
            int result = nums.Length;
            for (int i = 0; i < nums.Length; i++) {
                result ^= i ^ nums[i];
            }
            return result;
        }
    }
    

    Details worth knowing:

    • Length is a property of arrays, written without parentheses. A List<int> uses Count instead.
    • result ^= i ^ nums[i] means result = result ^ (i ^ nums[i]). The right side is evaluated first, and because XOR is associative the grouping doesn't change the answer.
    • No overflow risk. XOR never carries, so unlike a running sum it can't overflow an int.

    Complexity

    Time: O(n). One pass, two XORs per index. Space: O(1). A single int besides the loop variable.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] the method returns 2. That is why result starts at nums.Length and not at 0: starting at 0 would leave n out of the chain.
    • The missing number is 0. For [1] it returns 0. The XOR of 0 with anything leaves that thing unchanged, so 0 needs no special case.
    • A longer example. For [9,6,4,2,3,5,7,0,1], n is 9 and the method returns 8.
    • Summing instead. The formula n * (n + 1) / 2 minus the sum of nums also finds the answer, but for n = 100000 the total is about 5 billion, which doesn't fit in an int, so the sums need long. XOR avoids the question.
    • Duplicates. The method relies on the numbers being distinct. A repeated value would cancel itself and leave a wrong result.

    Testing

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