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?- A. 2 6 1
- B. 2 3 0
- C. 2 6 0
- 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
- Problem: Euler's totient φ(n) counts integers in 1..n coprime to n: φ(n) = n · Π (1 − 1/p) over distinct primes p dividing n, computed by…
- Problem: Find the maximum product len(w1) · len(w2) over pairs of words that share no letter, using a 26-bit letter mask per word. python…
- Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and…
- Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i]…
- Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder…