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
Trapping Rain Water with Python
More Relevant Posts
-
Day 25 of my Python learning journey Today I solved one of the most important sliding window problems. Problem: Longest Repeating Character Replacement Given a string s and an integer k, you can replace at most k characters. Find the length of the longest substring that can be made of the same character. Example: s = "AABABBA" k = 1 Output: 4 Because we can make "AABA" or "ABBA" → length = 4 What I tried first: Generate all substrings Count frequency each time Time Complexity → O(n²) ❌ Better approach: Sliding Window + Frequency Map Expand window using right Track max frequency inside window If window becomes invalid → shrink from left Code I wrote: s = "AABABBA" k = 1 count = {} left = 0 max_freq = 0 max_len = 0 for right in range(len(s)): count[s[right]] = count.get(s[right], 0) + 1 max_freq = max(max_freq, count[s[right]]) # condition: window size - max_freq > k if (right - left + 1) - max_freq > k: count[s[left]] -= 1 left += 1 max_len = max(max_len, right - left + 1) print(max_len) Problems I faced: I didn’t understand why we track only max_freq Confused about the condition (window size - max_freq > k) Thought we need to check all characters every time What I finally understood: We don’t need all frequencies… 👉 Only the most frequent character matters Time & Space Complexity: Time: O(n) Space: O(1) (since only 26 characters) Question: Why do we not decrease max_freq when shrinking the window? Today’s realization: Optimization is not about tracking everything… it’s about tracking the right thing #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Day 6 of my Python learning journey: Focusing on writing code that's not just functional, but also dependable. Highlights from today: - Warmed up by practicing iterators and generators. - Solved the "First Non-Repeating Character" problem using a clean two-pass frequency approach with O(n) complexity. - Merged two sorted arrays efficiently through the two-pointer technique (O(n + m))—avoiding any redundant sorting. - Developed a FastAPI endpoint for the above problem, complete with schema validation. Observations: Initially, I attempted a one-pass solution for the non-repeating character problem, but it ended up feeling convoluted. Switching to a two-pass strategy made the solution much more straightforward and maintainable. Current focus areas: - Maintaining input order integrity. - Performing input validation early on. - Keeping logic as simple as possible. - Thoroughly testing edge cases beforehand. Major takeaway: Define inputs/outputs upfront → validate data early → then prioritize optimization. Starting to grasp how even minor design decisions can significantly impact code quality. GitHub link: https://lnkd.in/gGPw8_js #Python #FastAPI #ProblemSolving #SoftwareEngineering #CleanCode #LearningInPublic #OOP #Testing
To view or add a comment, sign in
-
-
Day 16 of my Python learning journey Today I tried another interesting problem using the Two Pointer technique. Problem: Squares of a Sorted Array Given a sorted array, return a new array of the squares of each number, also sorted. Example: arr = [-4, -1, 0, 3, 10] Output: [0, 1, 9, 16, 100] What I understood: Even though the array is sorted, squaring negative numbers can break the order. So we cannot directly square and sort. Better approach (Two Pointer): Left pointer at start Right pointer at end Compare squares of both ends Place the larger square at the end of result array Code I wrote: arr = [-4, -1, 0, 3, 10] n = len(arr) result = [0] * n left = 0 right = n - 1 pos = n - 1 while left <= right: if abs(arr[left]) > abs(arr[right]): result[pos] = arr[left] * arr[left] left += 1 else: result[pos] = arr[right] * arr[right] right -= 1 pos -= 1 print(result) Problems I faced while coding this: At first I tried squaring and sorting, but it increased time complexity. I was confused about why we compare absolute values. The idea of filling the result array from the end was not clear initially. Managing three pointers (left, right, pos) felt tricky. What I finally understood: The largest square will always come from either end of the array. So we place it at the end and move inward. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(n) Question: Why do we fill the result array from the end instead of the beginning? Today’s realization: Sometimes the trick is not in solving directly, but in thinking from the result side. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Day 18: Today i explored how Python handles memory efficiently using Generators 🔹 What I learned and practiced: ✔️ Generators Functions that return an iterator and produce values one at a time. Great for saving memory when working with large datasets. ✔️ yield Keyword Used to produce a value and pause the function execution. It resumes from the same point when called again, unlike a normal return. ✔️ next() Function Used to retrieve the next value from the generator. Automatically stops when no more values are left to produce. ✔️ Created a square_gen() function to generate squares of numbers one by one. Key takeaway: Generators and yield are powerful tools for writing smarter, more efficient code by only processing what we need, when we need it.and also push in github #Python #codegnan #LearningPython
To view or add a comment, sign in
-
-
🐍 Day 8 of Learning Python — and things are getting real! Today's lab was all about writing code that doesn't break (or at least fails gracefully 😄). Here's what I worked through: ✅ Exception Handling — try / except / else / finally • Caught ZeroDivisionError, FileNotFoundError, ValueError, and TypeError • Used `raise` to throw custom error messages • Built my own exception class: TooSmallError 🎉 ✅ Standard library deep dive: • math — calculated circle areas, factorials, GCD, and compound interest • random — shuffled lists, simulated 1000 coin flips, generated reproducible sequences with seed() • datetime — parsed date strings, added time deltas, sorted ISO dates, and printed 5-day schedules ✅ Introspection with dir() and help() The biggest lesson today? Real-life programs don't always get perfect input. Learning to handle errors gracefully is just as important as writing the happy path. Day by day, the pieces are coming together. 💪 #Python #100DaysOfCode #LearningToCode #PythonProgramming #CodingJourney #Day8
To view or add a comment, sign in
-
Day 18 of my Python learning journey Today I tried another good problem based on the Two Pointer technique. Problem: Merge Sorted Array Given two sorted arrays, merge them into one sorted array. Example: arr1 = [1, 3, 5] arr2 = [2, 4, 6] Output: [1, 2, 3, 4, 5, 6] What I understood: Since both arrays are already sorted, we do not need to sort again. We can compare elements from both arrays and place the smaller one first. Better approach (Two Pointer): One pointer for arr1 One pointer for arr2 Compare both values Add the smaller value to the result Code I wrote: arr1 = [1, 3, 5] arr2 = [2, 4, 6] i = 0 j = 0 result = [] while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 while i < len(arr1): result.append(arr1[i]) i += 1 while j < len(arr2): result.append(arr2[j]) j += 1 print(result) Problems I faced while coding this: At first I thought I had to combine both arrays and then sort them. I was confused about why two pointers are enough. I also forgot to handle the remaining elements after one array finishes. What I finally understood: Because both arrays are sorted, we can merge them in one pass. This saves extra sorting work and makes the solution efficient. Time and Space Complexity: Time Complexity: O(n + m) Space Complexity: O(n + m) Question: What will be the output for: arr1 = [1, 2, 7] arr2 = [3, 4] Today’s realization: Sometimes the best solution is not creating something new, but combining what is already ordered. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
It’s not about the tool; it’s about the logic. I’ve realized that if the fundamentals are clear, simple scripts can solve complex problems. I built this Python tool to visualize the Break-Even Point—the exact moment a project shifts from cost to profit. By automating the calculation, I can spend less time on the math and more time on the strategy. The Takeaway: ✅ Clarity > Complexity: Simple inputs, powerful visual outcomes. ✅ Fundamentals First: Python is just the vehicle; engineering logic is the engine. I’m still learning, but I'm focusing on truly understanding how things work rather than just how to code them. What’s your take? Do we spend too much time learning tools and not enough time mastering the fundamentals? #MechanicalEngineering #PythonForEngineers #EngineeringMindset #LearningByDoing
To view or add a comment, sign in
-
🚀 **Day X of My Python Learning Journey – Mastering List Methods!** Today I explored one of the most important concepts in Python — **List Methods** 🐍 From adding elements to sorting and reversing, lists make data handling super powerful and flexible. Here are some key methods I practiced: ✔️ append() – Add elements ✔️ clear() – Remove all items ✔️ copy() – Duplicate lists ✔️ count() – Count occurrences ✔️ extend() – Add multiple elements ✔️ index() – Find position ✔️ insert() – Add at specific index ✔️ pop() – Remove by index ✔️ remove() – Remove specific value ✔️ reverse() – Reverse list ✔️ sort() – Sort elements 💡 **Key takeaway:** Understanding these methods makes your code cleaner, faster, and more efficient. Consistency is the real game changer — small progress every day leads to big results. 🔥 This is part of my **30 Days Python Challenge** — more coming soon! #Python #CodingJourney #100DaysOfCode #Programming #LearnPython #DeveloperLife #TechSkills #PythonLists
To view or add a comment, sign in
-
-
🐍 Day 26 of My 30-Day Python Learning Challenge 🚀 Today I enhanced my Log File Analyzer Project by adding a new feature. 📌 New Feature: Top N Words (User Choice) Instead of showing only top 3 words, users can now choose how many top words they want. 📌 Code: top_n = int(input("Enter number of top words: ")) top_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)[:top_n] print(top_words) --- 📊 What Changed? • Before → Fixed output (Top 3 words) • Now → Dynamic output (User-defined) --- 💡 Why this matters? • Makes the project flexible • Improves user experience • Closer to real-world applications --- 📊 Quick Question What will happen if user enters a very large number? A) Error B) Full list is returned C) Empty output D) Program stops Answer tomorrow 👇 #Python #MiniProject #ProjectEnhancement #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
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