DSA interview question
A city planner models a street of buildings as bar heights and asks how much rainwater would collect between them after a storm. Water above position i rises to the lower of the tallest wall on its left and the tallest wall on its right, minus the bar's own height. Precomputing left and right maximums works in O(n) extra space. The two-pointer version gets O(1) space: always move the side with the lower current wall, because that side's water level is already fully determined by its own running maximum.
Example: [0,1,0,2,1,0,1,3,2,1,2,1] → 6.
long long trap(const vector<int>& height);
| Input | Output | Explanation |
|---|---|---|
[0,1,0,2,1,0,1,3,2,1,2,1] | 6 | |
[4,2,0,3,2,5] | 9 | |
[3,0,2,0,4] | 7 | 3 + 1 + 3 |
[1,2,3] | 0 | Rising: nothing is held |
[2,0,2] | 2 | |
[5] | 0 |
(Confirm: heights are non-negative; bars have width 1; water spilling past either end is lost.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in