Problem Description
Given two numbers represented in base -2 as arrays of 0s and 1s (with the most significant bit first), return the result of adding these two negabinary numbers, also in array format without leading zeros.
Key Insights
- Negabinary (base -2) behaves differently than binary (base 2), especially regarding carries.
- Addition proceeds from the least significant digits to the most significant.
- The carry value can be negative or positive and needs to be carefully updated.
- The current digit is obtained with (sum mod 2) and the carry is updated as carry = -((sum - digit) / 2).
Space and Time Complexity
Time Complexity: O(max(n, m)), where n and m are the lengths of arr1 and arr2.
Space Complexity: O(max(n, m)) for storing the result.
Solution
We simulate the addition process from rightmost digits of arr1 and arr2. At each index, we calculate the sum by adding the corresponding digits and the current carry. The resulting digit is the remainder when divided by 2, and the carry is updated using the negabinary rule: carry = -((sum - digit) / 2). This process continues until all digits and the carry are processed. Finally, we remove any unnecessary leading zeros and reverse the result to return it in the correct order.