Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries).

Problem: Sum the minimum of every contiguous subarray using a monotonic stack (previous-less and next-less-or-equal boundaries).
def summin(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 i + 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] - i if st else n - i
        st.append(i)
    return sum(a[i] * left[i] * right[i] for i in range(n))
print(summin([2, 9, 7, 8, 3, 4, 6, 1]))
What is printed?
  1. A. 36
  2. B. 117
  3. C. 128
  4. D. 57

Correct answer: B. 117

Each a[i] is the minimum of left[i] × right[i] subarrays. For example 1 at the end is the minimum of all 8 subarrays ending there, and 2 is the minimum of the 7 subarrays starting at index 0 that stop before the 1. Summing a[i]·left·right gives 117, the same as the O(n²) brute force.

More Coding Interview Problems questions

Exams that ask this topic