This approach uses the formula for the sum of the first n natural numbers: Sum = n * (n + 1) / 2
. By calculating the sum of the numbers from the array and subtracting it from the expected sum, we can find the missing number.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), as no additional space is used beyond variables.
1function missingNumber(nums) {
2 const n = nums.length;
3 const total = n * (n + 1) / 2;
4 const sum = nums.reduce((acc, val) => acc + val, 0);
5 return total - sum;
6}
7
8// Usage
9const nums = [3, 0, 1];
10console.log("Missing number:", missingNumber(nums));
This JavaScript solution uses the reduce()
method to compute the sum of the array's elements and applies the arithmetic formula to find the missing number.
An efficient approach is using XOR. XORing a number with itself results in zero (n ^ n = 0), and XOR of any number with zero keeps the number unchanged (n ^ 0 = n). By XORing all indices and array elements together, each number present in both will cancel out, leaving the missing number.
Time Complexity: O(n), iterating through the array.
Space Complexity: O(1), using constant space.
1class Solution:
2 def missingNumber(self, nums):
3 xor_result = 0
4 for i, num in enumerate(nums):
5 xor_result ^= i ^ num
6 return xor_result ^ len(nums)
7
8# Usage
9nums = [3, 0, 1]
10sol = Solution()
11print(f"Missing number: {sol.missingNumber(nums)}")
Using XOR, the Python solution finds the missing number by cancelling pairs and retaining the non-paired value.