Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the number of distinct subarray sums of [1, 2, 3] (non-empty subarrays)? Run the code.

Problem: What is the number of distinct subarray sums of [1, 2, 3] (non-empty subarrays)? Run the code.
a = [1, 2, 3]
print(len({sum(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1)}))
What is printed?
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 7

Correct answer: A. 5

The subarray sums are 1, 2, 3, 3, 5, 6, so the distinct values are 1, 2, 3, 5 and 6.

More Coding Interview Problems questions

Exams that ask this topic