Skip to content

Commit 21ca7cd

Browse files
feat: add Single Number explanation
- XOR operation algorithm approach - Comprehensive problem analysis - Multiple approaches and optimizations - Edge cases and applications
1 parent db06ae8 commit 21ca7cd

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Single Number
2+
3+
## Problem Statement
4+
5+
Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one.
6+
7+
You must implement a solution with a linear runtime complexity and use only constant extra space.
8+
9+
## Examples
10+
11+
**Example 1:**
12+
```
13+
Input: nums = [2,2,1]
14+
Output: 1
15+
```
16+
17+
## Approach
18+
19+
### Method 1: XOR Operation (Recommended)
20+
1. Use XOR properties: a ^ a = 0, a ^ 0 = a
21+
2. XOR all elements in the array
22+
3. Result is the single number
23+
4. Most efficient approach
24+
25+
**Time Complexity:** O(n) - Single pass
26+
**Space Complexity:** O(1) - No extra space
27+
28+
### Method 2: Hash Set
29+
1. Use hash set to track seen numbers
30+
2. Remove when seen twice
31+
3. Less efficient than XOR approach
32+
33+
**Time Complexity:** O(n) - Single pass
34+
**Space Complexity:** O(n) - Hash set
35+
36+
## Algorithm
37+
38+
```
39+
1. Initialize result = 0
40+
2. For each num in nums:
41+
a. result = result ^ num
42+
3. Return result
43+
```
44+
45+
## Key Insights
46+
47+
- **XOR Properties**: a ^ a = 0, a ^ 0 = a
48+
- **Local Optimum**: XOR all elements efficiently
49+
- **Global Optimum**: Find single number
50+
- **Space Optimization**: Use only necessary space
51+
52+
## Alternative Approaches
53+
54+
1. **Hash Set**: Use hash set for tracking
55+
2. **Mathematical**: Use sum properties
56+
3. **Sorting**: Sort and find single number
57+
58+
## Edge Cases
59+
60+
- Single element: Return that element
61+
- Two elements: Return the single one
62+
- Large arrays: Handle efficiently
63+
- Negative numbers: Handle appropriately
64+
65+
## Applications
66+
67+
- Bit manipulation
68+
- Array algorithms
69+
- Algorithm design patterns
70+
- Interview preparation
71+
- System design
72+
73+
## Optimization Opportunities
74+
75+
- **XOR Operation**: Most efficient approach
76+
- **Space Optimization**: O(1) space complexity
77+
- **Linear Time**: O(n) time complexity
78+
- **No Extra Space**: Use only necessary space

0 commit comments

Comments
 (0)