Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays.

Problem: Find the total of the sums of ALL contiguous subarrays without enumerating them: element a[i] lies in (i + 1)·(n − i) subarrays.
def all_subarray_sums(a):
    n = len(a)
    return sum(x * (i + 1) * (n - i) for i, x in enumerate(a))
def brute(a):
    return sum(sum(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))
print(all_subarray_sums([4, 1, 3]), brute([4, 1, 3]), all_subarray_sums([2, -1, 2, 5]))
What is printed?
  1. A. 25 25 30
  2. B. 25 8 34
  3. C. 25 25 34
  4. D. 8 25 34

Correct answer: C. 25 25 34

A subarray containing index i picks its start among i + 1 positions and its end among n − i positions. [4, 1, 3]: 4·(1·3) + 1·(2·2) + 3·(3·1) = 12 + 4 + 9 = 25, matching the brute force 4 + 1 + 3 + 5 + 4 + 8. [2, −1, 2, 5]: 2·4 − 1·6 + 2·6 + 5·4 = 8 − 6 + 12 + 20 = 34. The contribution trick is O(n); the brute force is O(n³) (O(n²) with running sums). Just summing the array (8) ignores how often each element is counted.

More Coding Interview Problems questions

Exams that ask this topic