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
Valid Palindrome with Two Pointer Technique in Python
More Relevant Posts
-
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 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
-
-
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 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 11 of Python Learning: Loops and Patterns in Python Today I practiced loops in Python and learned how to create patterns using nested loops. This helps improve logic building and problem-solving skills. 🔹 What are Patterns? Patterns are shapes or number/star designs created using loops. They are great for understanding loop control and nested loops. 🔸 Using For Loop for i in range(5): print("*") 🔸 Star Pattern Example for i in range(1, 6): print("*" * i) Output: * ** 🔸 Number Pattern Example for i in range(1, 6): for j in range(1, i + 1): print(j, end=" ") print() 💡 Key Learning: Nested loops are useful when one loop runs inside another loop, especially for patterns and matrix-style problems. 🧪 Practice Task: ✔ Print reverse star pattern ✔ Print square pattern using stars ✔ Print number triangle pattern ✔ Try same patterns using while loop 🎯 Interview Question: What is a nested loop in Python? Answer: A nested loop is a loop inside another loop. It is used when repeated iterations are needed within each cycle of the outer loop. 📌 Day 11 completed — logic building step by step! #Python #Learning #CodingJourney #Day11 #Programming #SDET #100DaysOfCode Masai #dailyleaning #masaiverse
To view or add a comment, sign in
-
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
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 6 of my Python learning journey Today I tried solving a problem that looked easy at first, but understanding the logic took some time. Problem: Two Sum Given a list of numbers and a target value, find the indices of the two numbers that add up to the target. Example: nums = [4, 5, 1, 8] target = 9 Output: [0, 1] Because 4 + 5 = 9. Code I wrote: nums = [4, 5, 1, 8] target = 9 d = {} for i in range(len(nums)): num = nums[i] comp = target - num if comp in d: print("Indices:", d[comp], i) print("Values:", nums[d[comp]], nums[i]) break d[num] = i Problems I faced while coding this: At first I tried two nested loops, which worked but felt inefficient. I was confused about why we store numbers in a dictionary. The line d[num] = i also confused me because I didn’t understand why we save the index. It also took time to understand how comp = target - num helps find the pair. What I finally understood: Instead of checking every pair, we store numbers we have already seen in a dictionary. Then we check if the required number already exists. This reduces the time complexity from O(n²) to O(n). From tomorrow we will start something different. I’m planning to build a small Python project that will take about 1 week. Tomorrow I will share the project roadmap, and then we will start with Day 1 of the project. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
To view or add a comment, sign in
-
-
Today was one of those Python lessons that felt less like learning code and more like learning how to read its warnings properly. 🐍 Day 15 of my #30DaysOfPython journey was all about errors, and honestly, this topic matters because every developer runs into them. When Python code fails, it gives feedback that tells us where the issue is and what kind of problem it is. Learning to understand those messages makes debugging a lot faster. Today I went through the common ones: 1. SyntaxError — when the code is written incorrectly 2. NameError — when a variable has not been defined 3. IndexError — when an index goes out of range 4. ModuleNotFoundError — when a module cannot be found 5. AttributeError — when an attribute does not exist 6. KeyError — when the wrong key is used in a dictionary 7. TypeError — when an operation is applied to the wrong data type 8. ImportError — when something is imported incorrectly 9. ValueError — when the value is valid in type, but not in meaning 10. ZeroDivisionError — when a number is divided by zero What stood out to me today was how errors are not just problems — they are clues. Once you stop panicking and start reading them properly, debugging becomes a lot less intimidating. One more day, one more topic, one more step toward writing code with less guessing and more understanding. Which error has annoyed you the most while coding so far? #Python #LearnPython #CodingJourney #30DaysOfPython #Programming #DeveloperJourney
To view or add a comment, sign in
-
Day 3 of my Python & DSA learning journey 🚀 A simple string completely confused me today 🤯 "A man, a plan, a canal: Panama" — is this a palindrome? At first glance I thought — no way, there are too many symbols! But Python solved it in just a few lines. Here's what I learned today 👇 ❓ Valid Palindrome (Ignore Symbols) A palindrome is a word that reads the same forward and backward. Examples: madam racecar But what if the string contains spaces, commas, or symbols? Example: "A man, a plan, a canal: Panama" It is still a palindrome — we just need to ignore the non-alphanumeric characters. 📌 Python provides a very useful function for this: isalnum() → it checks whether a character is a letter or a number. 💻 Example in Python s = "A man, a plan, a canal: Panama" result = "" for ch in s: if ch.isalnum(): result += ch.lower() if result == result[::-1]: print("Palindrome") else: print("Not Palindrome") Output: Palindrome ✅ Here we: • Removed symbols using isalnum() • Converted characters to lowercase using .lower() • Compared the string with its reverse Just a few lines of code — problem solved! 🔥 🔥 Question for developers: Is "race a car" a valid palindrome according to this logic? Drop your answer in the comments and explain why 👇 👀 Day 4 Teaser Tomorrow I’ll share a very interesting string trick used in coding interviews: How to check if two strings are rotations of each other in just one line of Python. Stay tuned 🚀 #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming
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