Question presented to candidate: "You wrote the two-pointer solution to Trapping Rain Water. Convince me it is correct: the left pointer has not seen most of the right side, so why is leftMax enough to decide the water there? Walk me through it with Python code."
What a strong answer should cover:
- The per-bar formula: water = min(max to the left, max to the right) - h[i], and that the left pointer knows its left max exactly.
- The key bound: the right max seen so far is a lower bound on the true right wall of L, because unseen bars can only make it taller.
- The invariant: if leftMax <= rightMax, then level(L) = leftMax exactly, so L can be settled; otherwise settle R symmetrically.
- Why comparing heights (h[L] < h[R]) is also correct, and what goes wrong if you move the taller side.
- Complexity: each step settles one bar, so O(n) time; four variables, so O(1) extra space.
- Python details: Python ints cannot overflow, so the proof is the only thing to get right; tuple assignment like
side, i, used = "L", lo, left_maxkeeps the branch short, and a randomised test against a brute force is a few lines with plain lists.
Code / implementation expected: Optional — the two-pointer loop in Python 3 plus a short argument; a brute-force cross-check is a strong bonus.