Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: Minimum single-bit flips in a and b so that (a OR b) == c.

Problem: Minimum single-bit flips in a and b so that (a OR b) == c.
def min_flips(a, b, c):
    flips = 0
    while a or b or c:
        x, y, z = a & 1, b & 1, c & 1
        if z: flips += (x | y) == 0
        else: flips += x + y
        a >>= 1; b >>= 1; c >>= 1
    return flips
print(min_flips(6, 9, 5), min_flips(7, 7, 0), min_flips(1, 2, 3))
What is printed?
  1. A. 2 6 1
  2. B. 2 3 0
  3. C. 2 6 0
  4. D. 3 6 0

Correct answer: C. 2 6 0

Bits are independent. If c's bit is 1, one flip is needed only when both a and b have 0. If c's bit is 0, every 1 in a or b must be flipped – possibly 2 flips for one position. 6 = 0110, 9 = 1001, c = 0101: bits 1 and 3 each need one flip → 2. (7, 7, 0): three positions × 2 ones = 6 (counting positions, 3, is the trap). 1 | 2 = 3 already → 0. O(bits).

More Coding Interview Problems questions

Exams that ask this topic