Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick.
Problem: Enumerate all non-empty submasks of a mask with the s = (s − 1) & m trick.
m = 0b101101
s, cnt = m, 0
while s:
cnt += 1
s = (s - 1) & m
print(cnt)What is printed?- A. 45
- B. 64
- C. 15
- D. 32
Correct answer: C. 15
m has 4 set bits, so it has 2⁴ = 16 submasks including 0; the loop stops at 0, so it counts 15. (s − 1) & m steps to the next smaller submask, skipping the bits that m does not have.
More Coding Interview Problems questions
- 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 <…
- Problem: Print a matrix in spiral order. python def spiral(m): res = [] while m: res += m.pop(0) m = [list(r) for r in zip(m)][::-1]…