Missing Number
Master this topic with zero to advance depth.
Missing Number
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.
Examples
n = 3. Range is [0,3]. 2 is missing.
n = 2. Range is [0,2]. 2 is missing.
Level I: Brute Force (Sorting)
Intuition
Sort the array and check if each index matches the value at that index. The first index where nums[i] != i is the missing number. If all match, the missing number is .
Thought Process
- Sort
numsin ascending order. - Iterate from to :
- If
nums[i] != i, returni.
- If
- If loop finishes, return
n.
Pattern: Sorting
Level II: Math (Sum Formula)
Intuition
The sum of the first numbers is . By subtracting the sum of all elements in the array from this total sum, we obtain the missing number.
Level III: Optimal (XOR)
Intuition
XORing a number with itself results in 0 (). If we XOR all numbers in the range and all numbers in the array, every number present in the array will appear twice and cancel out, leaving only the missing number.
Thought Process
- Initialize
missing = n(or 0). - Iterate through the array:
missing ^= i ^ nums[i]
- Return
missing.
Pattern: XOR Cancellation
Detailed Dry Run
nums = [3, 0, 1], n = 3 missing = 3 i=0: missing = 3 ^ 0 ^ 3 = 0 i=1: missing = 0 ^ 1 ^ 0 = 1 i=2: missing = 1 ^ 2 ^ 1 = 2 Result: 2
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.