Start learning free

LESSON 306 OF 314 · BIT MANIPULATION

Missing Number in Swift: 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.count).
  • 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

    SWIFT · BIT MANIPULATION

    Missing Number in Swift, explained

    Problem overview

    The method missingNumber(_ nums: [Int]) -> Int receives an array of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent, and the method 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. For [0, 1] the answer is 2, because the missing number can be n itself. For [1] it is 0.

    The lesson asks for O(n) time and O(1) extra space.

    Approach: let equal numbers cancel

    A set of the values gives O(n) time but needs O(n) space. Sorting avoids the extra space but costs O(n log n). XOR meets both limits.

    XOR (^) has three properties that matter here: x ^ x is 0, x ^ 0 is x, and the order of operations doesn't matter. So when a group of numbers is XORed together, every number that appears twice cancels, and what remains is the XOR of the numbers that appear once.

    Here no number repeats, so the trick is to give every present number a partner. The indices of nums run from 0 to n - 1. Add n and you have every number from 0 to n, once each. XOR in all of those, then XOR in every value of nums. Each value in the array meets its equal among the indices and n, and the pair cancels. The missing number appears only among the indices and n, with no partner, so it is what is left.

    Step by step

    1. Start result at nums.count, which is n. It is a var. The indices stop at n - 1, so n has to be added at the start.
    2. Loop i over 0..<nums.count, which visits every index.
    3. XOR in the index and the value: result ^= i ^ nums[i].
    4. Return result.

    The solution in Swift

    class Solution {
        func missingNumber(_ nums: [Int]) -> Int {
            var result = nums.count
            for i in 0..<nums.count {
                result ^= i ^ nums[i]
            }
            return result
        }
    }
    

    The Swift details worth a closer look:

    • ^=. It is the compound assignment for XOR: result ^= v means result = result ^ v. In result ^= i ^ nums[i], the right side is computed first.
    • 0..<nums.count. The half-open range stops before nums.count, so i is always a valid index. Because nums.count is at least 1 here, the range is never inverted, but even for an empty array 0..<0 is a valid empty range.
    • No overflow. XOR never overflows, unlike a sum-based solution. Swift traps on overflow, so the XOR version has no overflow concern at all.

    Tracing [3, 0, 1]

    Here n is 3, so result starts at 3:

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

    After the first pass the 3s have cancelled, and 0 is XORed twice in total, once as index 0 and once as a value, so it cancels too. Only 2 has no partner, and the result is 2.

    Complexity

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

    Space: O(1). A single integer, result, is kept.

    Edge cases and common mistakes

    • The missing number is n. For [0, 1] the answer is 2. That is why result starts at nums.count rather than 0: otherwise n would never enter the XOR.
    • The missing number is 0. [1] gives 0, and [0] gives 1.
    • Starting at 0. Starting result at 0 leaves n uncancelled, and the final answer would be the missing number XOR n.
    • Looping to nums.count inclusive. Reading nums[nums.count] is out of range and crashes.
    • Distinct numbers. The cancelling argument relies on each value appearing once. An array with a repeated value breaks it.
    • A longer example. [9, 6, 4, 2, 3, 5, 7, 0, 1] has n = 9 and returns 8.

    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 Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free