Skip to content

Commit 623b49f

Browse files
feat: add Missing Number explanation
- Mathematical sum algorithm approach - Comprehensive problem analysis - Multiple approaches and optimizations - Edge cases and applications
1 parent 3fc272d commit 623b49f

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Missing Number
2+
3+
## Problem Statement
4+
5+
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.
6+
7+
## Examples
8+
9+
**Example 1:**
10+
```
11+
Input: nums = [3,0,1]
12+
Output: 2
13+
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
14+
```
15+
16+
## Approach
17+
18+
### Method 1: Mathematical Sum (Recommended)
19+
1. Calculate expected sum: n * (n + 1) / 2
20+
2. Calculate actual sum of array
21+
3. Return difference
22+
4. Most efficient approach
23+
24+
**Time Complexity:** O(n) - Single pass
25+
**Space Complexity:** O(1) - No extra space
26+
27+
### Method 2: XOR Operation
28+
1. Use XOR properties: a ^ a = 0, a ^ 0 = a
29+
2. XOR all numbers from 0 to n with array elements
30+
3. Less efficient than mathematical approach
31+
32+
**Time Complexity:** O(n) - Single pass
33+
**Space Complexity:** O(1) - No extra space
34+
35+
## Algorithm
36+
37+
```
38+
1. Calculate expected sum = n * (n + 1) / 2
39+
2. Calculate actual sum = sum of array elements
40+
3. Return expected sum - actual sum
41+
```
42+
43+
## Key Insights
44+
45+
- **Mathematical Sum**: Use arithmetic progression formula
46+
- **Local Optimum**: Calculate sum efficiently
47+
- **Global Optimum**: Find missing number
48+
- **Space Optimization**: Use only necessary space
49+
50+
## Alternative Approaches
51+
52+
1. **XOR Operation**: Use XOR properties
53+
2. **Sorting**: Sort and find missing number
54+
3. **Hash Set**: Use hash set for lookup
55+
56+
## Edge Cases
57+
58+
- Single element: Handle appropriately
59+
- Two elements: Handle appropriately
60+
- Large arrays: Handle efficiently
61+
- Empty array: Handle appropriately
62+
63+
## Applications
64+
65+
- Mathematical algorithms
66+
- Array manipulation
67+
- Algorithm design patterns
68+
- Interview preparation
69+
- System design
70+
71+
## Optimization Opportunities
72+
73+
- **Mathematical Sum**: Most efficient approach
74+
- **Space Optimization**: O(1) space complexity
75+
- **Linear Time**: O(n) time complexity
76+
- **No Extra Space**: Use only necessary space

0 commit comments

Comments
 (0)