Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum is counted exactly once: strict comparison on one side, non-strict on the other.

Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum is counted exactly once: strict comparison on one side, non-strict on the other.
def sum_mins(a):
    n = len(a); left = [0] * n; right = [0] * n; st = []
    for i in range(n):
        while st and a[st[-1]] > a[i]:
            st.pop()
        left[i] = i - (st[-1] if st else -1)
        st.append(i)
    st = []
    for i in range(n - 1, -1, -1):
        while st and a[st[-1]] >= a[i]:
            st.pop()
        right[i] = (st[-1] if st else n) - i
        st.append(i)
    return sum(a[i] * left[i] * right[i] for i in range(n))
print(sum_mins([4, 2, 5, 1]), sum_mins([3, 3, 3]))
What is printed?
  1. A. 21 18
  2. B. 21 9
  3. C. 18 18
  4. D. 21 30

Correct answer: A. 21 18

a[i] is the (designated) minimum of left[i] · right[i] subarrays: left[i] counts start positions back to the previous value ≤ a[i], right[i] counts end positions up to the next value < a[i]. [4, 2, 5, 1]: 4·1·1 + 2·2·2 + 5·1·1 + 1·4·1 = 4 + 8 + 5 + 4 = 21 (the 2 is the minimum of [4,2], [2], [4,2,5], [2,5]). [3, 3, 3] has 6 subarrays each with minimum 3 → 18. Using ≥ on both sides lets equal values claim the same subarray twice and gives 30. O(n).

More Coding Interview Problems questions

Exams that ask this topic