🔗LC136 🟢 Easy 🧩 Pattern – XOR
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
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.
Input: nums = [0,1]
Output: 2
Explanation:
n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.Code language: JavaScript (javascript)Solution
Bitwise XOR operator ^ is the only way to solve this question, personally, I don’t think we use it daily in programming hence this is more of a puzzle.
Since we have numbers from 0 to n, first we set the result to the nth number, and the for loop runs from 0 until n-1, so XOR of index and each number will cancel out all numbers to give us the missing number.
0^0^1^2^2 = 1
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function (nums) {
const numsLength = nums.length;
let result = numsLength;
for (let i = 0; i < numsLength; i++) {
result = result ^ i ^ nums[i];
}
return result;
};Code language: JavaScript (javascript)Alternate solution without XOR
This solution is based on the formula sum of n numbers = (n * (n + 1)) / 2;
calculatedSum - actualSum = missing number
var missingNumber = function(nums) {
const n = nums.length;
const expectedSum = (n * (n + 1)) / 2;
const actualSum = nums.reduce((sum, num) => sum + num, 0);
return expectedSum - actualSum;
};
let nums = [3, 0, 1];
console.log(missingNumber(nums)); // 2
Code language: JavaScript (javascript)