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?- A. 36
- B. 117
- C. 128
- 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
- Problem: Count the distinct non-empty substrings of a short string. python s = "ababa" print(len({s[i:j] for i in range(len(s)) for j in…
- Problem: Compute the KMP prefix function (pi[i] = length of the longest proper prefix of s[0..i] that is also its suffix). python def…
- Problem: Compute the Z-array (z[i] = length of the longest substring starting at i that matches a prefix of s; z[0] is set to 0). python…
- Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet…
- Problem: Rob houses arranged as a tree (node 0 is the root; parent[i] gives each node's parent). Directly linked houses cannot both be…
- Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have…