Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to emulate 32-bit wrap-around.
Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to emulate 32-bit wrap-around.
def add(a, b):
M = 0xFFFFFFFF
while b & M:
a, b = (a ^ b) & M, ((a & b) << 1) & M
a &= M
return a if a <= 0x7FFFFFFF else ~(a ^ M)
print(add(-3, 5), add(-8, -9))What is printed?- A. 2 -17
- B. 2 -15
- C. 8 -1
- D. -2 -1
Correct answer: A. 2 -17
XOR adds without carries and (a & b) << 1 is the carry; repeating until the carry is 0 gives the sum. Masking to 32 bits stops Python's infinite-precision negatives from looping forever, and ~(a ^ M) converts a 32-bit pattern back to a negative number: 2 and −17.
More Coding Interview Problems questions
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…
- Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, ……
- Problem: Compute a^b mod 1337 where the exponent b is given as a digit array (too large for an integer), using a^(10x + d) = (a^x)^10 ·…
- A stack supports push, pop and multipop(k) (pop up to k elements). Starting from empty, what is the worst-case total cost of any sequence…
- A binary counter starts at 0 and is incremented n times; each increment flips trailing 1s to 0 and one 0 to 1. What is the total number of…
- A service must detect whether a dependency graph with 10⁵ modules and 10⁶ edges has a cycle. Which approach is both correct and efficient?