Easybit-manipulation
Missing Number
Problem (restated)
Array of n distinct numbers in [0, n]. Find the missing one.
Intuition
XOR of 0..n with all nums cancels pairs; leftover is missing.
Approaches
XOR 0..n with nums
Tested onlyTime O(n)Space O(1)
Idea. x=0..n fold with nums.
Walkthrough. [3,0,1] → 2.
Trade-offs. Sum formula also O(n); XOR avoids overflow concerns in other langs.
Solution
export function missingNumber(nums: number[]): number {
let x = nums.length;
for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
return x;
}
export function missingNumber(nums: number[]): number {
let x = nums.length;
for (let i = 0; i < nums.length; i++) x ^= i ^ nums[i]!;
return x;
}
Template connection
Bit XOR identity (same family as single number).
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?