Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the sum of the lengths of all subarrays of an array of length 6? Run the code.

Problem: What is the sum of the lengths of all subarrays of an array of length 6? Run the code.
n = 6
print(sum(i * (n - i + 1) for i in range(1, n + 1)))
What is printed?
  1. A. 21
  2. B. 35
  3. C. 56
  4. D. 63

Correct answer: C. 56

Σ i·(n − i + 1) = 6 + 10 + 12 + 12 + 10 + 6 = 56. 21 counts the subarrays rather than their lengths, i·(n − i) gives 35, and 2⁶ − 1 = 63 counts subsets.

More Coding Interview Problems questions

Exams that ask this topic