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.
nums = [0,1,3]2nums = [0,1,2,3,4,5,6,7,9]8nums = [1,2,3]0lo = 0, hi = nums.length.mid = lo + (hi - lo) / 2.nums[mid] > mid: gap is in the LEFT half → set hi = mid.lo = mid + 1.lo == hi, that index is the missing number — return lo.After sorting, if no number is missing before index i, then nums[i] == i. The missing number creates a shift: every element at or after the gap satisfies nums[i] == i + 1. This is a monotone predicate — perfect for binary search. nums[mid] > mid tells us the gap happened at or before mid, so we shrink the search space left. Otherwise it is strictly to the right.
Sorting and scanning is O(n log n), and a hash set uses O(n) space. If the array is already sorted, binary search on whether index equals value also works.
The sum of 0 to n is n times n plus 1, over 2. Subtract the actual sum of the array, and what is left is the missing number. An exclusive or of all indexes and values works the same way, without any risk of overflow.
Expected sum minus actual sum gives the missing number. XOR of indexes and values is the overflow-safe twin.
Run the animation above on your own input, or watch the 1:13 video explanation of Missing Number with a dry run and Java code.