You are given an array nums containing n distinct numbers taken from the range [0, n].
Since one number in this range is missing, your task is to find that missing number.
Example:
Input: nums = [3, 0, 1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3].
2 is the missing number.
This solution uses the XOR (^) operator to find the missing number efficiently in O(n) time and O(1) extra space.
- Start with
xor = nums.length, since indices go from0ton-1but the range includesn. - For each index
iand corresponding numbernums[i], XOR them withxor. - Due to XOR properties:
a ^ a = 0(same numbers cancel out)a ^ 0 = a- XOR is commutative and associative
- Therefore, after XORing all indices and elements, only the missing number remains.
Input: nums = [3, 0, 1]
n = 3
| Step | i | nums[i] | xor before | Operation | xor after |
|---|---|---|---|---|---|
| Init | - | - | 3 | - | 3 |
| 1 | 0 | 3 | 3 | 3 ^ 0 ^ 3 | 0 |
| 2 | 1 | 0 | 0 | 0 ^ 1 ^ 0 | 1 |
| 3 | 2 | 1 | 1 | 1 ^ 2 ^ 1 | 2 |
β Final result: 2
class Solution {
public int missingNumber(int[] nums) {
int xor = nums.length;
for (int i = 0; i < nums.length; i++) {
xor ^= i ^ nums[i];
}
return xor;
}
}- Time Complexity: O(n)
β One pass through the array. - Space Complexity: O(1)
β Uses only a single integer variable.
| Method | Time | Space | Notes |
|---|---|---|---|
| XOR | O(n) | O(1) | Efficient and elegant bit manipulation approach |
- Bit Manipulation
- Array
- Math