Data Structures & AlgorithmsVery hardProduct company OA

A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack versions differ only in how the right-hand scan treats EQUAL weights. What is printed?

A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack versions differ only in how the right-hand scan treats EQUAL weights. What is printed?
def score(a, strict_right):
    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] if strict_right else 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))
a = [3, 1, 2, 1, 4]
print(score(a, False), score(a, True))
  1. A. 21 17
  2. B. 21 21
  3. C. 19 21
  4. D. 21 25

Correct answer: A. 21 17

a[i] contributes a[i] × left[i] × right[i], where the two spans count the subarrays in which a[i] is 'the' minimum. With duplicates, exactly one side may cross equal values. The left scan stops at the previous element ≤ a[i]; version 1's right scan pops ≥ and so stops only at a strictly smaller one – each subarray is credited to its leftmost… rightmost minimum exactly once, giving the true total 21 (brute force over the 15 subarrays agrees). Version 2 makes BOTH sides stop at an equal value, so a subarray containing both 1s is credited to neither: the 4 such subarrays are lost, 21 − 4 = 17. Making both sides cross equals would overcount instead.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic