Missing Number

EasyBit manipulation

nums holds n different numbers taken from the range 0 to n, so exactly one number of that range is missing. Return it.

Aim for O(n) time and O(1) extra space.

Examples

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

The range is 0 to 4, and 2 is the one not there.

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

Three numbers means the range is 0 to 3, so the missing one is 3, the top of the range.

Constraints

  • 1 ≤ n ≤ 10⁴, where n is nums.length
  • 0 ≤ nums[i] ≤ n
  • All values in nums are different.

Stuck?

Hint 1

You know the sum of every number from 0 to n. Compare it with the sum of nums.

Hint 2

Or XOR every index, n and every value together: each number that is present cancels itself out, and the missing one is left.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur