Data Structures & AlgorithmsHardProduct Company SDE · stack round

Problem: Sum the minimum of every non-empty subarray of [3, 1, 2, 4] by brute force.

Problem: Sum the minimum of every non-empty subarray of [3, 1, 2, 4] by brute force.
a = [3, 1, 2, 4]
print(sum(min(a[i:j + 1]) for i in range(len(a)) for j in range(i, len(a))))
What is printed?
  1. A. 17
  2. B. 15
  3. C. 19
  4. D. 21

Correct answer: A. 17

The ten subarrays have minima 3,1,1,1,1,1,1,2,2,4 which sum to 17. A monotone-stack solution computes the same total in O(n) by counting how many subarrays each element minimises.

More Coding Interview Problems questions

Exams that ask this topic