|
| 1 | +# Single Number II |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +Given an integer array `nums` where every element appears three times except for one, which appears exactly once. Find the single element and return it. |
| 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,3,2] |
| 14 | +Output: 3 |
| 15 | +``` |
| 16 | + |
| 17 | +## Approach |
| 18 | + |
| 19 | +### Method 1: Bit Manipulation (Recommended) |
| 20 | +1. Use bit manipulation to count bits |
| 21 | +2. For each bit position, count occurrences |
| 22 | +3. If count % 3 != 0, set that bit in result |
| 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 Map |
| 29 | +1. Use hash map to count occurrences |
| 30 | +2. Find element with count 1 |
| 31 | +3. Less efficient than bit manipulation |
| 32 | + |
| 33 | +**Time Complexity:** O(n) - Single pass |
| 34 | +**Space Complexity:** O(n) - Hash map |
| 35 | + |
| 36 | +## Algorithm |
| 37 | + |
| 38 | +``` |
| 39 | +1. Initialize result = 0 |
| 40 | +2. For each bit position (0 to 31): |
| 41 | + a. Count = 0 |
| 42 | + b. For each num in nums: |
| 43 | + - If (num >> i) & 1: count++ |
| 44 | + c. If count % 3 != 0: result |= (1 << i) |
| 45 | +3. Return result |
| 46 | +``` |
| 47 | + |
| 48 | +## Key Insights |
| 49 | + |
| 50 | +- **Bit Counting**: Count bits at each position |
| 51 | +- **Modulo 3**: Use modulo 3 to find single element |
| 52 | +- **Local Optimum**: Count bits efficiently |
| 53 | +- **Global Optimum**: Find single element |
| 54 | + |
| 55 | +## Alternative Approaches |
| 56 | + |
| 57 | +1. **Hash Map**: Use hash map for counting |
| 58 | +2. **Sorting**: Sort and find single element |
| 59 | +3. **Mathematical**: Use mathematical properties |
| 60 | + |
| 61 | +## Edge Cases |
| 62 | + |
| 63 | +- Single element: Return that element |
| 64 | +- All same: Return that element |
| 65 | +- Large arrays: Handle efficiently |
| 66 | +- Negative numbers: Handle appropriately |
| 67 | + |
| 68 | +## Applications |
| 69 | + |
| 70 | +- Bit manipulation |
| 71 | +- Array algorithms |
| 72 | +- Algorithm design patterns |
| 73 | +- Interview preparation |
| 74 | +- System design |
| 75 | + |
| 76 | +## Optimization Opportunities |
| 77 | + |
| 78 | +- **Bit Manipulation**: Most efficient approach |
| 79 | +- **Space Optimization**: O(1) space complexity |
| 80 | +- **Linear Time**: O(n) time complexity |
| 81 | +- **No Extra Space**: Use only necessary space |
0 commit comments