Skip to main content
All Questions

Calculate the trapped rainwater between bars in a given array.

Hard

Given an array of non-negative integers representing the heights of bars in a histogram, compute the amount of water that can be trapped between the bars after a rainfall.

The histogram is represented by an array where the width of each bar is 1. Water can be trapped if there are dips between taller bars that can hold the water.

Example

Input: [5, 0, 4] Output: 4 Explanation: Amount of water trapped is limited by shorter bar Input: [1, 1, 1] Output: 0 Explanation: No water can be trapped

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.