Trapping Rain Water with Python

Day 14 of my Python learning journey Today I worked on a problem that looks simple at first, but the logic behind it is very interesting. Problem: Trapping Rain Water Given an array where each element represents the height of bars, find how much water can be trapped after rain. Example: arr = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 What I understood: Water can only be trapped if there are taller bars on both sides. So for each position, we need: left max height right max height Water stored = min(left max, right max) - current height Better approach (Two Pointer): Instead of storing left and right max arrays, we can use two pointers: left pointer from start right pointer from end And track: left_max right_max Code I wrote: arr = [0,1,0,2,1,0,1,3,2,1,2,1] left = 0 right = len(arr) - 1 left_max = 0 right_max = 0 water = 0 while left < right: if arr[left] < arr[right]: if arr[left] >= left_max: left_max = arr[left] else: water += left_max - arr[left] left += 1 else: if arr[right] >= right_max: right_max = arr[right] else: water += right_max - arr[right] right -= 1 print(water) Problems I faced while coding this: At first I did not understand how water is calculated at each index. I was confused about why we compare left and right values. I also tried solving it using extra arrays, which increased space complexity. Understanding the role of left_max and right_max took time. What I finally understood: Instead of checking every index separately, we can decide from which side to move based on height. This helps us calculate trapped water in a single pass. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do we move the pointer from the side with the smaller height? Today’s realization: Some problems are not about brute force, but about understanding patterns and optimizing space. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming

  • text

hi mate just wanted to say well done on finishing the 14 days of python training that’s a solid effort and not everyone sticks it through like that quick thing that will help you a lot going forward keep focusing on how things work not just getting them to work the difference is massive over time if you really understand why something behaves a certain way you will always be able to fix it improve it or scale it later also try to build small real things even if they seem simple scripts tools little automations they add up fast and before you know it you’ve got a proper toolkit behind you keep going your on the right track

To view or add a comment, sign in

Explore content categories