Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: What is the sum of the lengths of all contiguous subarrays of [1, 2, 3]? Run the code.

Problem: What is the sum of the lengths of all contiguous subarrays of [1, 2, 3]? Run the code.
a = [1, 2, 3]
print(sum(len(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1)))
What is printed?
  1. A. 9
  2. B. 12
  3. C. 6
  4. D. 10

Correct answer: D. 10

Subarray lengths are 1,2,3 for start 0, 1,2 for start 1 and 1 for start 2, totalling 10.

More Coding Interview Problems questions

Exams that ask this topic