Data Structures & AlgorithmsVery hardProduct company OA
Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with asymmetric tie-breaking, gives O(n).
Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with asymmetric tie-breaking, gives O(n).
def sum_ranges(a):
n = len(a)
def total(better):
left = [0] * n; right = [0] * n; st = []
for i in range(n):
while st and better(a[i], a[st[-1]]): 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 (better(a[i], a[st[-1]]) or a[i] == a[st[-1]]): 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))
return total(lambda x, y: x > y) - total(lambda x, y: x < y)
def brute(a):
return sum(max(a[i:j]) - min(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))
print(sum_ranges([4, 1, 3, 3]), brute([4, 1, 3, 3]), sum_ranges([2, 5, 1]), brute([2, 5, 1]))What is printed?- A. 13 13 11 11
- B. 13 10 11 11
- C. 13 13 9 11
- D. 16 13 11 11
Correct answer: A. 13 13 11 11
Each a[i] is the maximum of left[i]·right[i] subarrays (and similarly the minimum), so Σ(max − min) = Σ a[i]·(count as max − count as min). Equal values (the two 3s) must be assigned to exactly one of them: strict on one side, non-strict on the other. [2, 5, 1]: ranges 0, 0, 0, 3, 4, 4 → 11. Brute force is O(n²) at best (O(n³) as written), far too slow for 2·10⁵.
More Coding Interview Problems questions
- Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i…
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…
- Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with…
- Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous…
- Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place…