Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Compute the amount of rain water trapped between bars.
Problem: Compute the amount of rain water trapped between bars.
def trap(h):
l, r = 0, len(h) - 1; lm = rm = water = 0
while l < r:
if h[l] < h[r]:
lm = max(lm, h[l]); water += lm - h[l]; l += 1
else:
rm = max(rm, h[r]); water += rm - h[r]; r -= 1
return water
print(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]), trap([4, 2, 0, 3, 2, 5]))What is printed?- A. 5 9
- B. 6 7
- C. 6 10
- D. 6 9
Correct answer: D. 6 9
Water above i = min(max left, max right) − h[i]. With two pointers, the side with the lower wall is bounded by its own running maximum, so it can be settled immediately. [4, 2, 0, 3, 2, 5] → 2 + 4 + 1 + 2 = 9. O(n) time, O(1) space.
More Coding Interview Problems questions
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…
- Problem: Given n ≤ 10⁵ words, find the longest chain where each word is the previous word with exactly one letter inserted (word length ≤…
- Problem: A string of length n = 10⁵; answer q = 10⁵ queries 'are substrings [l1, r1] and [l2, r2] equal?'. Which technique fits?
- Problem: n ≤ 40 items with weights up to 10⁹; count subsets with total weight ≤ W. Why is meet-in-the-middle preferred here?
- Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?