Bit manipulation · Easy
Missing Number: the idea to remember.
A length n array contains distinct values from zero through n except for one missing value. Find it.
The core insight
XOR all indices, all array values, and n. Paired values cancel.
Why it works
Each present value appears once in the complete range and once in the array. Only the missing value remains unpaired.
The mistake to avoid
Remember n, which has no corresponding array index. XOR avoids sum overflow.
Time: O(n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int missingNumber(int[] nums) {
int missing = nums.length;
for (int i = 0; i < nums.length; i++) missing ^= i ^ nums[i];
return missing;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.