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.
[0, n]
inclusive, where n
is the length of the array.[0, n]
.n
natural numbers is given by the formula ( \text{Sum} = \frac{n \times (n + 1)}{2} ).[0, n]
.#include <vector>
class Solution {
public:
int missingNumber(std::vector<int>& nums) {
int n = nums.size();
int expected_sum = n * (n + 1) / 2;
int actual_sum = 0;
for (int num : nums) {
actual_sum += num;
}
return expected_sum - actual_sum;
}
};
#include <vector>
class Solution {
public:
int missingNumber(std::vector<int>& nums) {
int n = nums.size();
int xor_sum = 0;
// XOR all indices and all values in the array
for (int i = 0; i <= n; ++i) {
xor_sum ^= i;
}
for (int num : nums) {
xor_sum ^= num;
}
return xor_sum;
}
};
Both approaches are efficient with ( O(n) ) time complexity and ( O(1) ) space complexity. The sum formula approach is more intuitive, while the bit manipulation approach may be considered more elegant by some due to the clever use of XOR properties. Both solutions will accurately solve the problem as per the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?