BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features54 of 54 in topic

843. Total water trapped between bars

MediumData processing and features Pro

You get a skyline of bars of width 1. After rain, water collects in the dips between taller bars. This is a classic test of whether you can turn a per-position rule into a single linear pass.

Write trapped_water(heights). heights is a list of non-negative integers. Return the total units of water held above the bars. Water above a position rises to the smaller of the tallest bar on its left and the tallest bar on its right, minus its own height, and never below zero.

Functiondef trapped_water(heights)

Example 1

Input: trapped_water([0, 2, 0, 1, 0, 3])

Output: 5

Example 2

Input: trapped_water([3, 2, 1])

Output: 0

Constraints

  • 0 <= len(heights) <= 100,000
  • 0 <= heights[i] <= 100,000
Hint 1

Write the per-position formula first.

Hint 2

Try prefix and suffix maximum arrays.

Hint 3

Then ask which side's maximum is the binding one.

Common mistakes
  • Using only the nearest taller bar instead of the tallest one.
  • Letting water go negative at peaks.
  • Off-by-one when the pointers meet.
Understand the idea

Many array puzzles reduce to a per-index formula built from a prefix and a suffix statistic. For [0, 2, 0, 1, 0, 3], the left maxima are 0, 2, 2, 2, 2, 3 and the right maxima are 3, 3, 3, 3, 3, 3, so the water is 0 + 0 + 2 + 1 + 2 + 0 = 5. Two pointers compute the same thing in one pass with O(1) memory.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
843 / 903
Python 3solution.pyPython idle
1
2
3
4
def trapped_water(heights):
# return the total trapped water
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS