Trapping Rainwater

Stack / Queues FAQs Hard
  • This problem, also known as the 'Trapping Rain Water' problem, is a prominent example of issues faced in space optimization
  • This kind of computational approach can be seen in real world applications like cache memory optimization in software applications, or file storage in hard disks where efficient use of space is required
  • Data scientists may also use the concept in analytics software, determining how best to utilize limited memory resources
  • Another practical use is in the gaming industry where such algorithms help in creating realistic water surface phenomena

Given an array of non-negative integers, height representing the elevation of ground. Calculate the amount of water that can be trapped after rain.

Examples:

Input: height= [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]

Output: 6

Explanation: As seen from the diagram 1+1+2+1+1=6 unit of water can be trapped


Input: height= [4, 2, 0, 3, 2, 5]

Output: 9

Expalanation: 2+4+1+2=9 unit of water can be trapped

Input: height= [7, 4, 0, 9]

Constraints

  •   n == height.length
  •   1 <= n <= 105
  •   0 <= height[i] <= 105

Hints

  • Compute left_max[i] → Maximum height from the left up to index i. Compute right_max[i] → Maximum height from the right up to index i. Water trapped at index i is: max(0, min({left_max}[i], {right_max}[i]) - {height}[i])
  • Use two pointers (left and right), tracking left_max and right_max. Always process the shorter side first, as it is the limiting factor for trapping water.

Company Tags

HCL Technologies Activision Blizzard Flipkart AMD JPMorgan Chase Twilio OYO Rooms Cloudflare Salesforce Qualcomm HashiCorp Snowflake Epic Games Target Bloomberg Shopify Nutanix NVIDIA Roche DoorDash Seagate Technology Rakuten Riot Games ARM Goldman Sachs Google Microsoft Amazon Meta Apple Netflix Adobe