Missing Number - Problem
You're given an array nums containing n distinct numbers taken from the range [0, n]. This means if the array has 3 elements, the numbers should come from [0, 1, 2, 3].
Here's the catch: exactly one number from this range is missing from the array. Your task is to find and return that missing number.
Example: If nums = [3, 0, 1], then n = 3 and the complete range should be [0, 1, 2, 3]. The missing number is 2.
Can you solve this efficiently? There are multiple clever approaches using math, bit manipulation, and more!
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3,0,1]
โบ
Output:
2
๐ก Note:
Array has 3 elements, so complete range should be [0,1,2,3]. Numbers 0, 1, 3 are present, but 2 is missing.
example_2.py โ Missing First
$
Input:
nums = [1]
โบ
Output:
0
๐ก Note:
Array has 1 element, so complete range should be [0,1]. Number 1 is present, but 0 is missing.
example_3.py โ Missing Last
$
Input:
nums = [0,1]
โบ
Output:
2
๐ก Note:
Array has 2 elements, so complete range should be [0,1,2]. Numbers 0 and 1 are present, but 2 is missing.
Constraints
- n == nums.length
- 1 โค n โค 104
- 0 โค nums[i] โค n
- All the numbers of nums are unique
Visualization
Tap to expand
Understanding the Visualization
1
Crime Scene Analysis
You know there should be n+1 pieces of evidence numbered 0 through n, but you only found n pieces.
2
The Brute Force Method
Check each possible evidence number by searching through your entire collection - slow but thorough.
3
The Hash Table Method
Create a quick-reference catalog of all evidence you have, then check which number isn't in your catalog.
4
The Mathematical Breakthrough
Use Gauss's discovery: the sum of numbers 0+1+2+...+n equals n(n+1)/2. The missing evidence number equals the difference between expected and actual sums!
Key Takeaway
๐ฏ Key Insight: Sometimes the most elegant solution comes from mathematical properties rather than complex algorithms. Gauss's sum formula transforms this from a search problem into a simple arithmetic calculation!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code