Blind 75 · Bit Manipulation

Missing Number

Easy

Watch the walkthrough (5:16)

Problem

An array nums holds n distinct numbers drawn from the range 0 to n — so exactly one number of that range is absent.
Return the missing number. The follow-up everybody gets: do it in O(n) time and O(1) space.

Examples

Example 1:
Input: nums = [3,0,1]
Output: 2

Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n is 2, the range is 0..2, and 2 is absent.

Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8

Example 4:
Input: nums = [0]
Output: 1

Constraints

1 <= nums.length <= 10^4
All values are distinct and within 0..nums.length.

Prerequisites

Binary and two's complement — how a negative number is stored, and what a shift does at the edges.
The trick worth memorising: n & (n-1) clears the lowest set bit.

How to think about it

1. XOR Everything Together Optimal

Intuition

The plain way puts the values in a set and checks 0, 1, 2 and on in turn: it works, but the set is O(n) extra space, and the follow-up asks for O(1). XOR needs one number. A number XORed with itself is 0, since every bit matches (5 ^ 5 = 0); XOR with 0 changes nothing (6 ^ 0 = 6); and the order does not matter. So fold the whole range, 0 to n, and every value into one number: each number that is there comes in twice, once from the range and once as a value, and cancels, and the missing number comes in once and survives. The indices are the range less n, so start with n. For [2,3,1,5,0], n is 5, 101: after four steps the running XOR is 000, and the last step brings in the index 4, whose value never comes, and the value 0, which changes nothing, so 4 survives. XOR the whole range with every value; what survives is the missing number.

Algorithm

1. Start missing at n, the length of nums: the one number of the range 0 to n that is not an index.
2. For each index i, XOR in i and nums[i].
3. Return missing: every number that is there has cancelled, and the missing number survives.

Time & Space

Time O(n): one pass, two XORs a step. Space O(1): one number kept, which is the follow-up.