Data Structures & AlgorithmsModerateTCS NQT · DP warm-up

Problem: How many ordered sequences of 1s and 3s sum to 6? Run the code.

Problem: How many ordered sequences of 1s and 3s sum to 6? Run the code.
ways = [1] + [0] * 6
for v in range(1, 7):
    for s in (1, 3):
        if v >= s:
            ways[v] += ways[v - s]
print(ways[6])
What is printed?
  1. A. 6
  2. B. 3
  3. C. 4
  4. D. 9

Correct answer: A. 6

Ordered sequences of 1s and 3s summing to 6: 111111, 33 and the 4 arrangements of one 3 with three 1s, so 6. Putting the step loop outside the target loop counts combinations (3), reading ways[5] gives 4, and reading ways[7] gives 9.

More Coding Interview Problems questions

Exams that ask this topic