Data Structures & AlgorithmsModerateCodeforces Div2 D · bitset DP

Problem: Subset sums of items [1, 2, 3] are computed with a bitset: reach starts as 1 and each item x does reach |= reach << x. How many distinct sums are reachable, including 0? Run the code.

Problem: Subset sums of items [1, 2, 3] are computed with a bitset: reach starts as 1 and each item x does reach |= reach << x. How many distinct sums are reachable, including 0? Run the code.
reach = 1
for x in [1, 2, 3]:
    reach |= reach << x
print(bin(reach).count('1'))
What is printed?
  1. A. 6
  2. B. 7
  3. C. 8
  4. D. 1

Correct answer: B. 7

Bit s of reach is set exactly when sum s is reachable; with 1, 2 and 3 every sum from 0 to 6 is reachable, so 7 bits are set. Leaving out the sum 0 gives 6, counting subsets (2³) instead of distinct sums gives 8 because 3 = 1 + 2, and writing reach <<= x without the OR keeps only the full sum (1).

More Coding Interview Problems questions

Exams that ask this topic