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?- A. 6
- B. 7
- C. 8
- 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
- Problem: Maximum number of events attended when each event is [start, end] (day-inclusive) and you can attend one event per day. Events…
- Problem: How many decimal digits does 100! have? Run the code. python import math print(len(str(math.factorial(100)))) What is printed?
- Problem: What is the digit sum of 100!? Run the code. python import math print(sum(int(c) for c in str(math.factorial(100)))) What is…
- Problem: Longest path in a weighted DAG from vertex 0 with edges 0->1 (3), 1->2 (4), 0->2 (10). Run the DP over the topological order…
- Problem: How many ordered sequences of jumps of sizes 2, 3 or 5 sum exactly to 12? Run the DP. python ways = [1] + [0] 12 for v in…
- Problem: What is the size of the largest divisible subset of [1, 2, 4, 8, 3] (every pair must satisfy one dividing the other)? Run the…