Missing Number
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
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
Input: nums = [3,0,1]
Output: 2
n = 3. Range is [0,3]. 2 is missing.
Input: nums = [0,1]
Output: 2
n = 2. Range is [0,2]. 2 is missing.
Approach 1
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
⏱ O(N log N) - Due to sorting.💾 O(1) or O(N) depending on the sort implementation.
Approach 2
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.
⏱ $O(N)$💾 $O(1)$
Approach 3
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
⏱ O(N) - Single pass through the array.💾 O(1) - Constant storage.
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
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.