Data Structures & AlgorithmsVery hardProduct company OA
Rain water trapped between bars, computed with two pointers. What is printed?
Rain water trapped between bars, computed with two pointers. What is printed?
def water(h):
l, r, lm, rm, w = 0, len(h) - 1, 0, 0, 0
while l < r:
if h[l] < h[r]:
lm = max(lm, h[l]); w += lm - h[l]; l += 1
else:
rm = max(rm, h[r]); w += rm - h[r]; r -= 1
return w
print(water([4, 0, 3, 1, 5, 0, 2, 0, 4]), water([5, 4, 3, 2, 1]), water([2, 0, 2, 0, 2]))- A. 18 10 2
- B. 18 0 4
- C. 14 0 4
- D. 17 0 4
Correct answer: B. 18 0 4
Move the side with the lower bar: the water above it is limited by its own side's running maximum, because the other side is already known to have a bar at least that tall. [4,0,3,1,5,0,2,0,4]: left part 4+1+3 = 8, right part 4+2+4 = 10, total 18. A strictly decreasing profile traps nothing. [2,0,2,0,2] traps 2 + 2. 10 is the decreasing case computed as if the right edge were a wall of height 5.
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
- Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed? python def…
- Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such…
- A ticket number may lose exactly k digits; the remaining digits must keep their order and form the smallest possible number (leading zeros…
- Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign…
- Longest subarray with sum exactly 5 when the array contains NEGATIVE numbers: a shrink-when-too-big sliding window versus a prefix-sum map…
- Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?…