Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max leaf on its right). Minimise the sum of internal nodes using a monotonic stack.
Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max leaf on its right). Minimise the sum of internal nodes using a monotonic stack.
def mct(a):
st, res = [float('inf')], 0
for x in a:
while st[-1] <= x:
mid = st.pop(); res += mid * min(st[-1], x)
st.append(x)
while len(st) > 2: res += st.pop() * st[-1]
return res
print(mct([3, 5, 2, 4]))What is printed?- A. 43
- B. 38
- C. 52
- D. 40
Correct answer: A. 43
Greedily remove the smallest leaf first, pairing it with its smaller neighbour: 2 with 4 (8), then 3 with 5 (15), then 4 with 5 (20), total 43. The stack does this in O(n) and matches the O(n³) interval DP over all tree shapes.
More Coding Interview Problems questions
- Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index. python def…
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…