Valid Palindrome with Two Pointer Technique in Python

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

  • text

To view or add a comment, sign in

Explore content categories