#1073
Adding Two Negabinary Numbers
MediumArrayMathBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach directly adds the two negabinary numbers without converting them to decimal. This is more efficient as it processes the bits in a single pass.
⚙️
Algorithm
7 steps- 1Step 1: Initialize an empty result array and a carry variable set to 0.
- 2Step 2: Iterate from the end of both arrays until both are exhausted.
- 3Step 3: For each position, calculate the sum of the bits and the carry.
- 4Step 4: Determine the new bit and the new carry based on the sum.
- 5Step 5: Append the new bit to the result array.
- 6Step 6: If there's a carry left after the loop, append it to the result.
- 7Step 7: Reverse the result array to get the final answer.
solution.py17 lines
1# Full working Python code
2
3def add_negabinary(arr1, arr2):
4 result = []
5 carry = 0
6 i, j = len(arr1) - 1, len(arr2) - 1
7 while i >= 0 or j >= 0 or carry:
8 total = carry
9 if i >= 0:
10 total += arr1[i]
11 i -= 1
12 if j >= 0:
13 total += arr2[j]
14 j -= 1
15 result.append(total % 2)
16 carry = -(total // 2)
17 return result[::-1]ℹ
Complexity note: The time complexity is O(n) because we process each bit of the input arrays once. The space complexity is O(n) for storing the result.
- 1Negabinary addition can be done directly without conversion to decimal.
- 2Understanding how to handle carries in negabinary is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.