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?
  1. A. 45
  2. B. 64
  3. C. 15
  4. 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

Exams that ask this topic