Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many ways are there to write 12 as a sum of distinct positive integers (partitions into distinct parts)? Run the DP.

Problem: How many ways are there to write 12 as a sum of distinct positive integers (partitions into distinct parts)? Run the DP.
dp = [1] + [0] * 12
for part in range(1, 13):
    for v in range(12, part - 1, -1):
        dp[v] += dp[v - part]
print(dp[12])
What is printed?
  1. A. 77
  2. B. 14
  3. C. 12
  4. D. 15

Correct answer: D. 15

The downward inner loop uses each part at most once, giving 15 distinct-part partitions of 12. Looping upward allows repeats (p(12) = 77), stopping parts at 11 misses {12} for 14, and dp[11] = 12 is one index short.

More Coding Interview Problems questions

Exams that ask this topic