LeetCode ยท #268
Missing Number Solution
Given array of n distinct numbers in [0, n], find the missing one.
01
Section One ยท Problem
Problem Statement
Example
Input: nums = [3,0,1]
Output: 2 // range [0,3], missing 2
02
Section Two ยท Approach 1
Sort โ O(n log n)
Sort and find where nums[i] != i.
Better: Gauss sum:
expected = n*(n+1)/2, subtract actual sum. Or XOR: XOR [0..n] with all elements โ pairs cancel, missing remains.03
Section Three ยท Approach 2
Sum Formula or XOR โ O(n), O(1)
Sum: n*(n+1)/2 - sum(nums). XOR: XOR all indices [0..n] with all elements. Duplicates cancel, missing remains.
๐ก Mental model (sum): You know the sum of a complete set. The actual sum is less โ the difference is the missing piece. Like counting money: expected $55, got $53, missing $2.
๐ก XOR variant: XOR index 0 with nums[0], index 1 with nums[1], ..., index n (the extra index) with nothing. All present numbers pair up (index โ value), leaving the missing one.
04
Section Four ยท Trace
Visual Walkthrough
Missing Number โ Sum Formula
05
Section Five ยท Implementation
Code โ Java & Python
Java โ XOR
class Solution {
public int missingNumber(int[] nums) {
int xor = nums.length;
for (int i = 0; i < nums.length; i++)
xor ^= i ^ nums[i];
return xor;
}
}
Python โ Sum formula
class Solution:
def missingNumber(self, nums: list[int]) -> int:
n = len(nums)
return n * (n + 1) // 2 - sum(nums)
06
Section Six ยท Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Sort | O(n log n) | O(1) |
| HashSet | O(n) | O(n) |
| Sum / XOR โ optimal | O(n) | O(1) |
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Missing 0 | [1] | expected=1, actual=1โฆ wait, n=1, expected=1 โ 1-1=0. Missing 0. |
| Missing n | [0,1,2] | n=3, expected=6, actual=3, missing=3. |
| Single element | [0] | Missing 1. n=1, 1-0=1. |
โ Common Mistake: Sum formula can overflow for very large n with 32-bit ints. Use
long or XOR (no overflow risk). Python has arbitrary precision so no issue there.