LeetCode 268: Missing Number

Search for a command to run...

No comments yet. Be the first to comment.
Question Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times. [0,1,2,4,5,6,7] if it was rotated 7 times. No...

Problem Overview Given an integer n, return an array ans of length n + 1 where ans[i] is the number of set bits in the binary representation of i. Example: n = 5 → Output: [0, 1, 1, 2, 1, 2] Constraints: 0 <= n <= 10^5 Solution 1: Brute Force Thi...

Problem Overview The goal is to write a function that takes an unsigned integer and returns the number of ‘1’ bits it has in its binary representation. This value is also known as Hamming weight. This is the classic bit manipulation problem. Solution...

Bruce Lin
4 posts
class Solution {
public:
int missingNumber(vector<int>& nums) {
int result = nums.size();
for (int i = 0; i < nums.size(); i++) {
result ^= i ^ nums[i];
}
return result;
}
};
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.
Example 1:
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 in the range since it does not appear in nums.
This question asks us to find the only missing number, so we can use the XOR ^ bit operation. It means that 0 ^ x = x, x ^ x = 0. Take example 1, for instance, the input nums are 3, 0, 1, and the full numbers are 0, 1, 2, 3.
Therefore, we can XOR all of them: 3^0^1^0^1^2^3 = (3^3) ^ (2) ^ (1^1) ^ (0^0) = 2. As we can see, the answer is 2.
The problem gives us two sets of numbers: the complete range [0, n] and the incomplete input nums. Since only one number is missing, XORing all elements from both sets together will cause every number that appears in both sets to cancel itself out, leaving only the missing number.
x ^ x = 0
x ^ 0 = x
Example: nums = [3, 0, 1]
n: nums.size() is 3
Complete Range: {0, 1, 2, 3}
Input nums: {3, 0, 1}
Combined XOR: (0 ^ 1 ^ 2 ^ 3) ^ (3 ^ 0 ^ 1)
Rearrange & Cancel: (3 ^ 3) ^ (2) ^ (1 ^ 1) ^ (0 ^ 0) = 2
The result is the missing number, 2.
Time: O(n)
Space: O(1)