Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in Scala: 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.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

    SCALA · BIT MANIPULATION

    Missing Number in Scala, explained

    Problem overview

    The method missingNumber(nums: Array[Int]): Int receives n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent from nums. The method returns it.

    For [3, 0, 1], n is 3 and the numbers should be 0, 1, 2 and 3. The array has 0, 1 and 3, so the answer is 2. For [0, 1] the missing number is n itself, 2, and for [1] it is 0.

    Approach: give every value a partner

    A set of the values, or a sum formula, would also find the answer. The statement asks for O(n) time and O(1) space, and XOR does it with one number of state and no risk of overflow.

    XOR has three properties that matter here: x ^ x = 0, x ^ 0 = x, and the order of the operands doesn't matter. So XORing a collection of numbers cancels every number that appears twice and leaves the one that appears once.

    In this problem no value repeats, but we can make partners. The indices of nums are 0 to n - 1, and adding n gives every number from 0 to n exactly once. XOR all of those together with all the values in nums. Each value in nums appears twice (once as a value, once among the indices and n) and cancels. The missing number appears only among the indices and n, so it is what remains.

    Step by step

    1. Create var result and start it at nums.length, which is n. The indices stop at n - 1, so n goes in here.
    2. Loop over every index with for (i <- nums.indices). nums.indices is the range 0 to n - 1.
    3. Inside the loop, XOR both the index and the value into result.
    4. Return result.

    The solution in Scala

    class Solution {
        def missingNumber(nums: Array[Int]): Int = {
            var result = nums.length
            for (i <- nums.indices) {
                result ^= i ^ nums(i)
            }
            return result
        }
    }

    Scala details

    • ^ is bitwise XOR on Int, and ^= is the compound form. result ^= i ^ nums(i) XORs the already combined i ^ nums(i) into result; operator order doesn't change the outcome here, since XOR is associative.
    • nums.indices gives a Range from 0 to nums.length - 1, so there is no off-by-one with until or to.
    • nums(i) reads an array element with parentheses, not square brackets.
    • var result is needed because the loop reassigns it. The parameter nums is never changed.

    Tracing [3, 0, 1]

    result starts at 3. After each index:

    i=0 value=3 result=0
    i=1 value=0 result=1
    i=2 value=1 result=2

    The final value is 2, the missing number. At index 0, 3 ^ 0 ^ 3 is 0, since the 3 from the start and the 3 in the array cancel.

    Complexity

    Time is O(n): one pass with two XORs per index. Space is O(1): a single integer. Unlike summing 0 + 1 + ... + n, XOR never produces a number larger than the inputs, so there is no overflow to think about.

    Edge cases and common mistakes

    • The missing number is n: [0, 1] returns 2. That works only because result starts at nums.length. Starting at 0 would return 0 here.
    • The missing number is 0: [1] returns 0, and the result is correct because XORing with 0 changes nothing.
    • Single element: [0] returns 1.
    • A longer example: [9, 6, 4, 2, 3, 5, 7, 0, 1] returns 8.
    • Forgetting one side: XORing only the values, or only the indices, leaves a mix of numbers instead of the answer. Both sides are needed so that the present values cancel.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free