AAlgoLoopSpaced repetition for LeetCode
EASYBit ManipulationLeetCode ↗

Missing Number

The key idea

Every index 0..n-1 and every value share the full set 0..n except for the one missing number. XOR each index with each value: identical numbers cancel to 0, leaving only the missing one. The Gauss sum n*(n+1)/2 minus the actual sum gives the same answer in O(1) space.

Problem

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Bit Manipulation problems