Find Missing Number in Sequence
Learn how to find the missing number in a sequence using simple math and XOR approaches with clear examples and real-world applications.
π’ Find Missing Number in Sequence
This is a classic Blind 75 problem that tests how well you understand
mathematical formulas and bit manipulation.
Youβre given a range of numbers, but one is missing β your task is to find it efficiently.
π Problem Statement
Given an array containing n distinct numbers taken from the range [0, n],
find the only number missing from the array.
Example
Input: nums = [3, 0, 1]
Output: 2Explanation: Numbers from 0 to 3 should be [0, 1, 2, 3],
but 2 is missing.
π‘ Approach 1 β Using Sum Formula
We know that the sum of numbers from 0 to n is:
sum = n * (n + 1) / 2If we subtract the actual sum of the array from this total sum,
the result will be the missing number.
Steps
- Find the expected sum using the formula
- Find the actual sum from the array
- Subtract actual from expected β thatβs the missing number
Python Code
def missing_number(nums):
n = len(nums)
total = n * (n + 1) // 2
actual = sum(nums)
return total - actual
print(missing_number([3, 0, 1])) # Output: 2π§ Why this works:
The total sum represents what the array should have.
Removing what it actually has leaves behind the missing piece.
βοΈ Approach 2 β Using XOR (Bit Manipulation)
This approach doesnβt use extra space or big numbers β itβs based on XOR logic.
Key idea
- XOR of two same numbers is 0
- XOR of 0 with any number is that number itself
So if we XOR all indices and all numbers in the array,
the missing number will remain as the final result.
Python Code
def missing_number(nums):
n = len(nums)
result = 0for i in range(n + 1): result ^= i
for num in nums: result ^= num
return result
print(missing_number([9,6,4,2,3,5,7,0,1])) # Output: 8π§© Why this works:
Every number that appears twice (once as index, once as value) cancels out β
the missing one doesnβt, so itβs left behind.
π Real-World Example
Imagine youβre managing an order tracking system.
Orders are numbered sequentially from 0 to n.
If one record is missing, you can detect which order ID was skipped.
orders = [0, 1, 3, 4, 5]
print("Missing Order ID:", missing_number(orders))
# Output: Missing Order ID: 2This helps identify missing entries due to data loss or system errors.
π§ Key Takeaways
- β Sum Formula β Simple, clean, works for small-to-medium numbers
- β XOR Method β Memory efficient, handles large ranges safely
- π§ Used in systems where IDs or indexes are expected to be continuous
π Challenge for You
Try modifying the problem where two numbers are missing
and see if you can adapt the logic to find both!
π Related Topics
- Bit Manipulation
- Array Math
- Parity and XOR properties
- Data validation in ordered sequences
---