How do you trap rain water given an elevation map?

DSA
Hard
147.7K views

Calculate the total amount of water that can be trapped after raining given an array of non-negative integers representing heights. This tests two-pointer and stack-based approaches.

Why Interviewers Ask This

This complex problem evaluates advanced problem-solving skills and the ability to visualize spatial relationships. Interviewers look for candidates who can break down the problem into finding the left and right boundaries for each bar. It demonstrates mastery of two-pointer techniques or stack-based monotonic structures.

How to Answer This Question

Explain the concept that water level at any index depends on the minimum of the max height to its left and right. Describe the two-pointer approach where you move pointers inward based on which side has a smaller boundary. Alternatively, discuss the stack approach for maintaining decreasing heights. Provide a visual trace of a small example. Analyze time and space complexities for both methods.

Key Points to Cover

  • Water level dependency on boundaries
  • Two-pointer movement logic
  • Max height tracking mechanism
  • O(n) time and O(1) space efficiency

Sample Answer

The most efficient solution uses two pointers moving from both ends towards the center. We maintain the maximum height seen so far from the left and right. At each step, if the left height is smaller, we calculate trappe…

Common Mistakes to Avoid

  • Calculating water without considering boundaries
  • Moving pointers incorrectly based on current height
  • Overcomplicating with unnecessary data structures

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 107 DSA questions