Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c.
Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c.
def flips(a, b, c):
res = 0
while a or b or c:
x, y, z = a & 1, b & 1, c & 1
if z == 0: res += x + y
elif x == 0 and y == 0: res += 1
a, b, c = a >> 1, b >> 1, c >> 1
return res
print(flips(9, 12, 6))What is printed?- A. 3
- B. 4
- C. 5
- D. 2
Correct answer: B. 4
9 = 1001, 12 = 1100, 6 = 0110. Bit 0: c = 0 but a = 1 (1 flip). Bit 1: c = 1 but both 0 (1 flip). Bit 2: b already 1. Bit 3: c = 0 but both are 1 (2 flips). Total 4; the trap is counting only 1 for bit 3.
More Coding Interview Problems questions
- Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick. python m = 0b101101 s, cnt = m, 0 while s: cnt += 1 s…
- A bitmask DP loops over every mask of n bits and, for each mask, over all of its submasks. What is the total number of (mask, submask)…
- Problem: A dynamic array doubles its capacity when full (starting at capacity 1), copying all elements to the new storage. Count element…
- Problem: A Rabin–Karp search uses a weak hash (the sum of character codes) and verifies every hash hit. Count true matches and spurious…
- Problem: Find the longest proper prefix of s that is also a suffix (the 'happy prefix'). python def happy(s): p = [0] len(s); k = 0 for i…
- Problem: Generate the 'look-and-say' sequence starting from '1'. python def nxt(s): out, i = [], 0 while i < len(s): j = i while j <…