Question presented to candidate: "You are given a list of non-negative integers where each number is the height of a bar of width 1. Write a Python function that computes how many units of rain water are trapped between the bars."
What a strong answer should cover:
- The per-bar formula: water[i] = min(max height to the left, max height to the right) - h[i], with both maxima including i.
- A progression of solutions: brute force O(nยฒ); prefix/suffix max arrays O(n) time and O(n) space; monotonic stack; two pointers O(n) time and O(1) space.
- Why two pointers is correct: settle the lower side, because the other side already has a wall at least that tall.
- Edge cases: fewer than 3 bars, monotonic arrays, flat arrays.
- Python details:
itertools.accumulate(h, max)builds the prefix-max array in one line, slicing likemax(h[:i + 1])hides an O(n) copy, and a negative index such ash[-1]silently reads the last bar instead of failing.
Clarifying questions expected:
- Can heights be negative, and are bars all width 1?
- Is O(n) extra space acceptable?
Code / implementation expected: Yes โ trap(height: list[int]) -> int with two pointers, in Python 3.