Day 15 of my Python learning journey: Today I tried a problem with a very interesting name. Problem: Container With Most Water The name itself made me curious. You are given an array where each element represents the height of a vertical line. You have to find two lines such that they form a container that can hold the maximum amount of water. Example: arr = [1,8,6,2,5,4,8,3,7] Output: 49 What I understood: The amount of water depends on: width (distance between two lines) height (minimum of the two lines) Water = width × min(height) Better approach (Two Pointer): Start one pointer from the left Start one pointer from the right Then: • Calculate area • Move the pointer with smaller height Code I wrote: arr = [1,8,6,2,5,4,8,3,7] left = 0 right = len(arr) - 1 max_area = 0 while left < right: width = right - left height = min(arr[left], arr[right]) area = width * height if area > max_area: max_area = area if arr[left] < arr[right]: left += 1 else: right -= 1 print(max_area) Problems I faced while coding this: At first I tried checking all pairs, which was too slow. I did not understand why we move the pointer with smaller height. It felt wrong to ignore some pairs, but the logic still worked. What I finally understood: Moving the smaller height pointer helps us try to find a better height while reducing width. This avoids unnecessary comparisons and makes the solution efficient. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do we always move the pointer with the smaller height? Today’s realization: Sometimes the best solution is not checking everything, but skipping the right things. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
Container With Most Water Problem Solution in 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 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
-
-
Day 17 of my Python learning journey Today I tried another interesting problem using the Two Pointer technique. Problem: Valid Palindrome Given a string, check if it can become a palindrome after removing at most one character. Example: s = "abca" Output: True Because removing 'c' makes it "aba" which is a palindrome. What I understood: We need to check if the string is almost a palindrome, allowing one mistake. Better approach (Two Pointer): Start one pointer from left Start one pointer from right If characters match → move both pointers If mismatch → try skipping one character (either left or right) Code I wrote: def is_palindrome(s, left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True s = "abca" left = 0 right = len(s) - 1 while left < right: if s[left] != s[right]: if is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1): print(True) else: print(False) break left += 1 right -= 1 else: print(True) Problems I faced while coding this: At first I tried removing every character and checking, which was inefficient. I was confused about which character to remove when mismatch happens. Writing a helper function for checking palindrome took some time to understand. What I finally understood: At the first mismatch, we only need to try two cases: skip left character skip right character If any one works, the string is valid. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: What will be the output for: s = "abc" Today’s realization: Sometimes solving a problem is about allowing one controlled mistake. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🐍 Day 7 of Learning Python — and things are getting real! Today's session was all about making Python programs robust and practical. Here's what I covered: 🔴 Python Errors & Exception Handling → Understood common errors: ZeroDivisionError, ValueError, NameError, IndexError, FileNotFoundError → Learned try / except / else / finally to handle errors gracefully instead of crashing → Used Exception as e to catch and print meaningful error messages 📐 Math Module → sqrt(), pow(), ceil(), floor(), and math.pi — Python makes math clean and simple 🎲 Random Module → randint(), randrange(), choice(), choices(), and shuffle() — great for building games and simulations 📅 DateTime Module → Getting today's date, formatting with strftime(), and doing date arithmetic with timedelta 🗂️ OS Module → Navigating the file system with listdir(), getcwd(), mkdir(), and rmdir() — right from Python! The biggest mindset shift today? Errors aren't failures — they're information. Wrapping code in try/except means your program can fail gracefully and keep going. 💡 7 days in and I'm genuinely enjoying every session. The journey continues! 🚀 #Python #100DaysOfCode #LearningInPublic #PythonProgramming #CodingJourney #Day7 #LearnPython #PythonDeveloper #CodeNewbie #TechLearning #Programming #SoftwareDevelopment #Coding #DataScience #MachineLearning #AI #TechCommunity #Developer #OpenToWork #Upskilling #Growth #StudentLife #PythonBeginners #CodeEveryDay #ProgrammingLife #Tech #Innovation #LinkedInLearning #CareerGrowth #FutureOfTech
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 9 of learning Python Today was all about diving deep into the "What if?" of programming. I spent the day exploring how to make my code more resilient and user-friendly by mastering Bugs and Exceptions in Python. 🐍💻 Here’s a breakdown of the key takeaways from my learning documentary today: 1. The Anatomy of a Mistake: Bugs vs. Exceptions Not all errors are created equal. I learned to distinguish between the two major categories: Bugs: These are the logic flaws. The program might run to the end, but it gives the wrong answer—like a calculator saying 2+2=5. Exceptions: These are the "show-stoppers." They happen during execution and will crash the program immediately if they aren't handled. 2. Identifying the Culprits I spent time matching specific error types to their causes. Recognizing these early is a superpower for any developer: SyntaxError: You missed a colon or a bracket. IndexError: You tried to access the 10th item in a list that only has 5. ValueError: You tried to turn the word "Apple" into an integer. NameError: You called a variable that hasn't been defined yet. 3. The Power of try/except The most exciting part of today was learning how to predict the unpredictable. Instead of letting a program crash when an error occurs, I can use a try/except block. The try block tests a piece of code. The except block provides a "safety net" to catch the error and keep the program running smoothly. 🛡️ The big lesson? A good developer doesn't just write code that works; they write code that knows what to do when things go wrong. Onwards to the next challenge! 📈 #Python #CodingJourney #SoftwareDevelopment #LearningToCode #TechSkills #ErrorHandling #PythonProgramming #Sololearn
To view or add a comment, sign in
-
-
Day 20 of my Python learning journey Today I worked on a problem that completely changed how I look at arrays. At first, it looked like a normal question… But the solution came from a linked list concept. Problem: Find the Duplicate Number (O(1) Space) You are given an array of size n + 1 containing numbers from 1 to n. There is only one duplicate number, but it can appear multiple times. Find the duplicate without modifying the array and using constant space. Example: arr = [1, 3, 4, 2, 2] Output: 2 What I tried first: Using a set → works but uses extra space Sorting → modifies the array Both were not allowed. What I learned today: We can treat the array like a linked list. Each index → node Value → next pointer This creates a cycle, and the duplicate number is where the cycle starts. Optimized approach: Floyd’s Cycle Detection Slow pointer moves 1 step Fast pointer moves 2 steps Step 1: Find the meeting point inside the cycle Step 2: Find the starting point of the cycle (duplicate) Code: def findDuplicate(arr): # Step 1: Detect cycle (meeting point) slow = arr[0] fast = arr[0] while True: slow = arr[slow] fast = arr[arr[fast]] if slow == fast: break # Step 2: Find cycle start (duplicate) slow = arr[0] while slow != fast: slow = arr[slow] fast = arr[fast] return slow # Example arr = [1, 3, 4, 2, 2] print(findDuplicate(arr)) Problems I faced while solving this: I could not understand how an array can behave like a linked list The idea of cycle detection in arrays felt confusing I kept going back to sorting and hashing methods What I finally understood: This problem is not about arrays… It’s about recognizing hidden patterns. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do fast and slow pointers always meet inside a cycle? Today’s realization: Sometimes the solution is not in the data structure you see… but in the one you don’t see at first. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Day 15 of Python Learning: Inheritance in Python Today I learned about Inheritance in Python — one of the most important concepts of Object-Oriented Programming (OOP). It helps reuse code and build relationships between classes. 🔹 What is Inheritance? Inheritance allows one class to use the properties and methods of another class. 🔸 Parent Class Example class Animal: def sound(self): print("Animal makes sound") 🔸 Child Class Example class Dog(Animal): pass dog1 = Dog() dog1.sound() 🔸 Overriding Method Example class Dog(Animal): def sound(self): print("Dog barks") dog1 = Dog() dog1.sound() 🔸 Benefits of Inheritance ✔ Code reusability ✔ Better structure ✔ Easy maintenance ✔ Supports hierarchy 💡 Key Learning: Child classes can inherit from parent classes and also customize behavior when needed. 🧪 Practice Task: ✔ Create a Vehicle parent class ✔ Create Car child class ✔ Add method start() ✔ Override one method in child class 🎯 Interview Question: What is the difference between inheritance and polymorphism in Python? Answer: Inheritance allows code reuse from another class, while polymorphism allows the same method name to behave differently in different classes. 📌 Day 15 completed — growing stronger in Python OOP! #Python #Learning #CodingJourney #Day15 #Programming #SDET #100DaysOfCode Masai #dailylearning #masaiverse
To view or add a comment, sign in
-
Day 11 of my Python learning journey Today I tried solving the Two Sum problem using the Two Pointer technique. Before this, I was only solving Two Sum using a dictionary. But today I learned another approach that works when the array is sorted. Problem: Two Sum (Two Pointer Approach) Given a sorted array and a target value, find two numbers whose sum equals the target. Example: nums = [1, 2, 4, 6, 10] target = 8 Output: [2, 6] Because 2 + 6 = 8. What is the Two Pointer technique? Two pointers means using two positions in the array: one pointer starts from the left side one pointer starts from the right side Then we move them based on the sum. How it works: • If the sum is too small, move the left pointer forward • If the sum is too large, move the right pointer backward • If the sum equals the target, we found the answer Code: nums = [1, 2, 4, 6, 10] target = 8 left = 0 right = len(nums) - 1 while left < right: s = nums[left] + nums[right] if s == target: print(nums[left], nums[right]) break elif s < target: left += 1 else: right -= 1 Problems I faced while coding this: At first I did not understand why the array needs to be sorted. I was confused about when to move the left pointer and when to move the right pointer. I also tried using this method on an unsorted array and it did not work. What I finally understood: The Two Pointer technique works well when the array is sorted because it lets us adjust the sum efficiently without checking every pair. This reduces the time complexity compared to nested loops. Question: Would this approach still work if the array was not sorted? #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
🚀 Today’s Learning: Python Conditional Statements (if, elif, nested if) 🧠🐍 Today in class, I learned how decision-making works in Python using if, elif, and nested if statements. 🔹 Key Takeaways: ✔️ if-else → Used when there are two possible outcomes (True / False) ✔️ if-elif-else → Used when checking multiple conditions (order matters ⚠️) ✔️ nested if → Used for multi-level decision making (filter → then decide) ✔️ Writing clean and optimized code is as important as writing working code 💡 One important lesson: 👉 “Code running ≠ Code correct” 👉 Logic and optimization make a real difference in programming 🔧 Also learned about common mistakes like: ❌ Wrong condition order ❌ Indentation errors ❌ Repeating unnecessary code 📌 Practiced real examples like: Marks grading system Discount calculation Finding largest number Even/Odd check with proper logic This session helped me understand how to think logically while coding, not just write code. #Python #LearningJourney #DataScience #Programming #CodingBasics #IfElse #LogicBuilding #StudentLife
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