EASY NC#148 Blind #14 Bit Manipulation
268. Missing Number
๐ Problem
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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use XOR property: a ^ a = 0, a ^ 0 = a
- โ XOR all indices 0..n with all array values
- โ Duplicate numbers cancel out, leaving missing number
- โ Initialize result with n, then XOR with i and nums[i]
- โ Time: O(n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse XOR property: a ^ a = 0, a ^ 0 = a
- โขXOR all indices 0..n with all array values
- โขDuplicate numbers cancel out, leaving missing number
Common Pitfalls
- โขInitialize result with n, then XOR with i and nums[i]
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
missingNumber([3,0,1]); Expected:
2 Test Case 2
Not run Input:
missingNumber([0,1]); Expected:
2 Test Case 3
Not run Input:
missingNumber([9,6,4,2,3,5,7,0,1]); Expected:
8 ๐ Code Editor
๐ค Output