Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

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

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.size).
  • 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

    KOTLIN · BIT MANIPULATION

    Missing Number in Kotlin, explained

    Problem overview

    The function missingNumber receives an IntArray named nums with n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent. The function returns it.

    For nums = [3, 0, 1], n is 3, so the numbers 0, 1, 2 and 3 should all appear. Only 2 is absent, so the answer is 2. The missing number can also be n itself, as in [0, 1] where the answer is 2, or 0, as in [1] where the answer is 0.

    Approach: let XOR cancel the pairs

    Sorting or a hash set would find the missing number, but the statement asks for O(n) time and O(1) extra space. A sum of 0 to n minus the sum of the array also works. This lesson uses XOR instead.

    XOR has three properties that matter here: x xor x is 0, x xor 0 is x, and the order of the operands doesn't matter. So when a collection of numbers is XOR-ed together, every number that appears twice disappears, and a number that appears once is what is left.

    Here no value repeats, so we have to create the partners. The indices of nums run from 0 to n - 1. Add n, and the indices together with n contain every number from 0 to n exactly once. The values in nums contain the same numbers except the missing one. XOR all of them together, and each number present in nums meets its twin among the indices and cancels. The missing number has no twin among the values, so it is the only one left.

    Step by step

    1. Start result at nums.size, declared with var. This is n, which the indices never reach, so it goes in at the start.
    2. Loop i over nums.indices, the range 0 to n - 1.
    3. XOR in both the index and the value: result = result xor i xor nums[i].
    4. Return result.

    The solution in Kotlin

    class Solution {
        fun missingNumber(nums: IntArray): Int {
            var result = nums.size
            for (i in nums.indices) {
                result = result xor i xor nums[i]
            }
            return result
        }
    }
    

    For nums = [3, 0, 1], result starts at 3 and changes like this:

    start result=3
    i=0 nums[i]=3 result=0
    i=1 nums[i]=0 result=1
    i=2 nums[i]=1 result=2
    

    The final value, 2, is the missing number.

    The Kotlin details worth knowing:

    • XOR is xor. Kotlin has no ^ operator. xor is an infix function on Int, and chaining a xor b xor c evaluates from left to right.
    • nums.indices is an IntRange from 0 to nums.size - 1. It is the idiomatic way to loop over positions without writing the bounds.
    • No overflow. XOR never produces a bit that neither operand has, so it can't overflow. A solution that adds the numbers 0 to n could: for n = 100000 the sum is 5,000,050,000, which doesn't fit in an Int, so it would need a Long.

    Complexity

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

    Space: O(1). The function keeps a single number.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1], result starts at 2, and the loop cancels 0 and 1. The 2 is never cancelled, so the answer is 2. This is why result starts at nums.size rather than 0.
    • The missing number is 0. For [1], the loop XORs 0 and 1 into the starting 1 and leaves 0.
    • Starting at 0. Then n is never cancelled, and the function returns the missing number XOR n instead of the missing number itself.
    • Using or or and instead of xor. Only XOR cancels a number against itself.
    • A single element. [0] returns 1, because n = 1 is the missing number.

    Testing

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