Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA
Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars.
Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars.
h=[4,2,0,3,2,5,1,0,2] print(sum(max(0,min(max(h[:i+1]),max(h[i:]))-h[i]) for i in range(len(h))))What is printed?
- A. 31
- B. 12
- C. 14
- D. 21
Correct answer: B. 12
Water above each bar is min(left max, right max) minus its height. Summing the water level without subtracting the bar height counts the bars themselves, adding a stray constant is a careless slip, and using only the left running maximum overfills the right side.
More Coding Interview Problems questions
- The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps?…
- Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and…
- How many ways are there to tile a 3 × 8 board completely with 1 × 2 dominoes (placed horizontally or vertically)? Count by DFS over the…
- Meetings are given as half-open intervals [(0,30),(5,10),(15,20),(12,25),(28,35)]. What is the minimum number of meeting rooms needed so…
- Count the unordered pairs (i < j) of the array a = [1, 2, ..., 14] whose sum is divisible by 3. Run the code. python a=list(range(1,15))…
- Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code…