Magicsheet logo

Adding Two Negabinary Numbers

Medium
100%
Updated 6/1/2025

Asked by 1 Company

Topics

Adding Two Negabinary Numbers

What is this problem about?

The Adding Two Negabinary Numbers coding problem is a challenging math-based question. "Negabinary" is a non-standard positional numeral system where the base is 2-2 instead of 22. You are given two arrays representing negabinary numbers and must return their sum as an array.

Why is this asked in interviews?

This problem is a favorite at Grab because it tests a candidate's ability to adapt a well-known algorithm (binary addition) to a completely different set of rules. It tests mathematical flexibility and the ability to handle unusual "carries" (in negabinary, the carry can be 1,0, or 1-1, 0, \text{ or } 1).

Algorithmic pattern used

This follows the Math Simulation interview pattern. Just like standard binary addition, you work from the least significant bit (end of the array) to the most significant. However, the carry logic is derived from the fact that (2)n+(2)n=2×(2)n=(2)n+1(-2)^n + (-2)^n = -2 \times (-2)^n = (-2)^{n+1}. In negabinary, if the sum at a position is 2, the carry to the next position is actually 1-1.

Example explanation

In base 2-2:

  • 1 is 11
  • 110 is (2)2+(2)1=42=2(-2)^2 + (-2)^1 = 4 - 2 = 2 Adding 1 + 110 (which is 1+2=31 + 2 = 3):
  1. Rightmost bit: 1+0=11 + 0 = 1. Carry 0.
  2. Next bit: 0+1=10 + 1 = 1. Carry 0.
  3. Next bit: 0+1=10 + 1 = 1. Carry 0. Result: 111 (42+1=34 - 2 + 1 = 3).

Common mistakes candidates make

  • Standard Carry Logic: Using a carry of +1 when the sum is 2. In negabinary, 1+11+1 at index ii results in 00 at ii and 1-1 as a carry for i+1i+1.
  • Leading Zeros: Returning an array like [0, 0, 1, 1] instead of [1, 1].
  • Sign Confusion: Not realizing that even positions have positive weights (1,4,161, 4, 16) and odd positions have negative weights (2,8,32-2, -8, -32).

Interview preparation tip

When dealing with base 2-2, remember the rule: if the sum SS at a position is greater than 1, you can set the current bit to S2S-2 and set the carry to 1-1. If the sum is 1-1, set the current bit to 11 and the carry to 11.

Similar Questions