|
| 1 | +# Add Binary |
| 2 | + |
| 3 | +## Problem Statement |
| 4 | + |
| 5 | +Given two binary strings `a` and `b`, return their sum as a binary string. |
| 6 | + |
| 7 | +## Examples |
| 8 | + |
| 9 | +**Example 1:** |
| 10 | +``` |
| 11 | +Input: a = "11", b = "1" |
| 12 | +Output: "100" |
| 13 | +``` |
| 14 | + |
| 15 | +## Approach |
| 16 | + |
| 17 | +### Method 1: Two Pointers (Recommended) |
| 18 | +1. Use two pointers from right to left |
| 19 | +2. Add digits with carry |
| 20 | +3. Handle carry propagation |
| 21 | +4. Most efficient approach |
| 22 | + |
| 23 | +**Time Complexity:** O(max(m, n)) - Where m, n are string lengths |
| 24 | +**Space Complexity:** O(max(m, n)) - Result string |
| 25 | + |
| 26 | +### Method 2: Built-in Functions |
| 27 | +1. Convert to integers, add, convert back |
| 28 | +2. Less efficient for large numbers |
| 29 | + |
| 30 | +**Time Complexity:** O(max(m, n)) - Conversion and addition |
| 31 | +**Space Complexity:** O(max(m, n)) - Result string |
| 32 | + |
| 33 | +## Algorithm |
| 34 | + |
| 35 | +``` |
| 36 | +1. Initialize pointers at end of both strings |
| 37 | +2. Initialize carry = 0 |
| 38 | +3. While pointers valid or carry exists: |
| 39 | + a. Sum = digit1 + digit2 + carry |
| 40 | + b. Result digit = sum % 2 |
| 41 | + c. Carry = sum / 2 |
| 42 | + d. Move pointers left |
| 43 | +4. Reverse result and return |
| 44 | +``` |
| 45 | + |
| 46 | +## Key Insights |
| 47 | + |
| 48 | +- **Two Pointers**: Process from right to left |
| 49 | +- **Carry Handling**: Handle carry propagation |
| 50 | +- **Local Optimum**: Add digits efficiently |
| 51 | +- **Global Optimum**: Complete binary addition |
| 52 | + |
| 53 | +## Alternative Approaches |
| 54 | + |
| 55 | +1. **Built-in Functions**: Use Integer.parseInt() |
| 56 | +2. **String Manipulation**: Use string operations |
| 57 | +3. **Recursive**: Use recursive approach |
| 58 | + |
| 59 | +## Edge Cases |
| 60 | + |
| 61 | +- Empty strings: Handle appropriately |
| 62 | +- Different lengths: Pad with zeros |
| 63 | +- All zeros: Return "0" |
| 64 | +- Large numbers: Handle efficiently |
| 65 | + |
| 66 | +## Applications |
| 67 | + |
| 68 | +- Binary arithmetic |
| 69 | +- String manipulation |
| 70 | +- Algorithm design patterns |
| 71 | +- Interview preparation |
| 72 | +- System design |
| 73 | + |
| 74 | +## Optimization Opportunities |
| 75 | + |
| 76 | +- **Two Pointers**: Most efficient approach |
| 77 | +- **Space Optimization**: O(max(m, n)) space complexity |
| 78 | +- **Linear Time**: O(max(m, n)) time complexity |
| 79 | +- **No Extra Space**: Use only necessary space |
0 commit comments