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))- A. 21 17
- B. 21 21
- C. 19 21
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed? python from collections…
- atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed? python def…
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…