Adding Two Negabinary Numbers - Problem

Given two numbers arr1 and arr2 in base -2, return the result of adding them together.

Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -8 + 4 + 1 = -3.

A number arr in array format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.

Return the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.

Input & Output

Example 1 — Basic Addition
$ Input: arr1 = [1,1,0,1], arr2 = [1,0,1]
Output: [1,0,0]
💡 Note: arr1 represents (-2)³+(-2)²+(-2)⁰ = -8+4+1 = -3. arr2 represents (-2)²+(-2)⁰ = 4+1 = -1. Sum: -3+(-1) = -4, which in base -2 is [1,0,0] = (-2)² = 4.
Example 2 — Simple Case
$ Input: arr1 = [1], arr2 = [1]
Output: [1,1,0]
💡 Note: Both arrays represent -1 in base -2. Sum: -1+(-1) = -2, which in base -2 is [1,1,0] = (-2)²+(-2)¹ = 4+(-2) = 2. Wait, let me recalculate: [1] = (-2)⁰ = 1, so 1+1 = 2, which in base -2 is [1,1,0].
Example 3 — Zero Result
$ Input: arr1 = [1], arr2 = [1,1]
Output: [0]
💡 Note: arr1 = [1] represents 1. arr2 = [1,1] represents (-2)¹+(-2)⁰ = -2+1 = -1. Sum: 1+(-1) = 0.

Constraints

  • 1 ≤ arr1.length, arr2.length ≤ 1000
  • arr1[i] and arr2[i] are 0 or 1
  • arr1 and arr2 have no leading zeros except when representing 0

Visualization

Tap to expand
Adding Two Negabinary Numbersarr1 = [1,1,0,1]represents -3arr2 = [1,0,1]represents -1result = [1,0,0]represents -4addBase -2: Each position i represents (-2)^i-3 + (-1) = -4(-2)³ + (-2)² + (-2)⁰ + (-2)² + (-2)⁰ = (-2)²
Understanding the Visualization
1
Input Arrays
Two negabinary arrays representing numbers
2
Addition Process
Add with proper base -2 carry handling
3
Result
Sum in negabinary format without leading zeros
Key Takeaway
🎯 Key Insight: Handle carries in base -2 by managing negative powers properly
Asked in
Google 15 Facebook 8
15.0K Views
Medium Frequency
~25 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen